DateTime.ToString方法

前言

将当前 DateTime 对象的值转换为其等效的字符串表示形式。

Converts the value of the current DateTime object to its equivalent string representation.

参考:DateTime.ToString 方法 (System) | Microsoft Docs


输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
zh-CN
d 2021/8/18
D 2021818
f 202181812:48
F 202181812:48:39
g 2021/8/18 12:48
G 2021/8/18 12:48:39
m 818
o 2021-08-18T12:48:39.5960000+00:00
r Wed, 18 Aug 2021 12:48:39 GMT
s 2021-08-18T12:48:39
t 12:48
T 12:48:39
u 2021-08-18 12:48:39Z
U 202181812:48:39
Y 20218

en-US
d 8/18/2021
D Wednesday, August 18, 2021
f Wednesday, August 18, 2021 12:48 PM
F Wednesday, August 18, 2021 12:48:39 PM
g 8/18/2021 12:48 PM
G 8/18/2021 12:48:39 PM
m August 18
o 2021-08-18T12:48:39.5970000+00:00
r Wed, 18 Aug 2021 12:48:39 GMT
s 2021-08-18T12:48:39
t 12:48 PM
T 12:48:39 PM
u 2021-08-18 12:48:39Z
U Wednesday, August 18, 2021 12:48:39 PM
Y August 2021

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Globalization;

public class Example
{
public static void Main()
{
// Create an array of all supported standard date and time format specifiers.
string[] formats = {"d", "D", "f", "F", "g", "G", "m", "o", "r", "s", "t", "T", "u", "U", "Y"};
// Create an array of four cultures.
CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("zh-CN"),
CultureInfo.CreateSpecificCulture("en-US")};
// Iterate each standard format specifier.
foreach (CultureInfo culture in cultures)
{
Console.WriteLine(culture.Name);
foreach (string formatSpecifier in formats)
{
Console.WriteLine("{0} {1}", formatSpecifier, DateTime.Now.ToString(formatSpecifier, culture));
}
Console.WriteLine();
}
}
}


后记

可以直接用 .NET 在线编辑器 试试效果。