DateTime.ToString(string format) 中 format 参数(区分大小写):
参数 含义
d 月中的某一天。一位数的日期没有前导零。
dd 月中的某一天。一位数的日期有一个前导零。
ddd 周中某天的缩写名称,在 AbbreviatedDayNames 中定义。
dddd 周中某天的完整名称,在 DayNames 中定义。
M 月份数字。一位数的月份没有前导零。
MM 月份数字。一位数的月份有一个前导零。
MMM 月份的缩写名称,在 AbbreviatedMonthNames 中定义。
MMMM 月份的完整名称,在 MonthNames 中定义。
y 不包含纪元的年份。如果不包含纪元的年份小于 10,则显示不具有前导零的年份。
yy 不包含纪元的年份。如果不包含纪元的年份小于 10,则显示具有前导零的年份。
yyyy 包括纪元的四位数的年份。
gg 时期或纪元。如果要设置格式的日期不具有关联的时期或纪元字符串,则忽略该模式。
h 12 小时制的小时。一位数的小时数没有前导零。
hh 12 小时制的小时。一位数的小时数有前导零。
H 24 小时制的小时。一位数的小时数没有前导零。
HH 24 小时制的小时。一位数的小时数有前导零。
m 分钟。一位数的分钟数没有前导零。
mm 分钟。一位数的分钟数有一个前导零。
s 秒。一位数的秒数没有前导零。
ss 秒。一位数的秒数有一个前导零。
f 秒的小数精度为一位。其余数字被截断。
ff 秒的小数精度为两位。其余数字被截断。
fff 秒的小数精度为三位。其余数字被截断。
ffff 秒的小数精度为四位。其余数字被截断。
fffff 秒的小数精度为五位。其余数字被截断。
ffffff 秒的小数精度为六位。其余数字被截断。
fffffff 秒的小数精度为七位。其余数字被截断。
使用如下:
System.DateTime.Now.ToString("D");
//2019年9月20日
System.DateTime.Now.ToString("d");
//2019-9-20
System.DateTime.Now.ToString("F");
//2019年9月20日 15:46:34
System.DateTime.Now.ToString("f");
//2019年9月20日 15:46
System.DateTime.Now.ToString("G");
//2019-9-20 15:46:34
System.DateTime.Now.ToString("g");
//2019-9-20 15:46
System.DateTime.Now.ToString("T");
//15:46:34
System.DateTime.Now.ToString("t");
//15:46
System.DateTime.Now.ToString("U");
//2019年9月20日 15:46:34
System.DateTime.Now.ToString("u");
//2019-9-20 15:46:34Z
System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff");
//2019-9-20 15:46:34
System.DateTime.Now.ToString("yyyy年MM月dd HH时mm分ss秒");
//2019年09月20 15时46分34秒
System.DateTime.Now.ToString("dddd, MMMM dd yyyy");
//星期五, 九月 20 2019
this.TextBox2.Text = System.DateTime.Now.ToString("ddd, MMM d \\'yy");
//五, 九月 20 '19
System.DateTime.Now.ToString("dddd, MMMM dd");
//星期五, 九月 20
System.DateTime.Now.ToString("M/yy");
//9-19
System.DateTime.Now.ToString("dd-MM-yy");
//20-09-19
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
System.DateTime.Now转换为字符串的方法:
//获取当前系统时间
DateTime dt = System.DateTime.Now;
//将系统时间转换成字符串
string strTime = dt.ToString();
//长日期字符串
string strTime = dt.ToLongDateString();
//短日期字符
string strTime = dt.ToShortDateString();
//长时间字符串
string strTime = dt.ToLongTimeString();
//短时间字符串
string strTime = dt.ToShortTimeString();
//yyyyMMdd
string strTime = dt.ToString("yyyyMMdd");
//yyyy-MM-dd HH:mm
string strTime = dt.ToString("yyyy-MM-dd HH:mm");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
转换结果:
ToString : 2019-9-20 15:46:34
ToLongDateString : 20019年9月20日
ToShortDateString : 2019-9-20
ToLongTimeString : 15:46:34
ToShortTimeString : 15:46
1
2
3
4
5
字符串转换自定义分隔符的方法:
// 系统时间 2019-9-20 15:46:34
DateTime dt = System.DateTime.Now;
string date1 = string.Format("{0:yyyy}-" + "{0:MM}-" + "{0:dd}", dt );
//输出:2019-9-20
string date1 = string.Format("{0:yyyy} | " + "{0:MM} | " + "{0:dd}", dt );
//输出:2019 | 09 | 20