说明
字符串的格式化指将字符串变更为某一格式,例如某一种日期格式
本文参考[C# 开发实战] 软件开发技术联盟编著
语法
string S3= string.Format("Current Time is {0:d}",dt);
格式规范 | 说明 |
---|---|
d | 简短日期格式(YYYY-MM-DD) |
D | 完整日期格式(YYYY年MM月DD日) |
t | 简短时间格式(hh:mm) |
T | 完整时间格式(hh:mm:ss) |
f | 简短日期时间格式(YYYY年MM月DD日 hh:mm) |
F | 完整日期时间格式(YYYY年MM月DD日 hh:mm:ss) |
g | 简短可排序日期时间格式(YYYY年MM月DD日 hh:mm) |
G | 简短可排序日期时间格式(YYYY年MM月DD日 hh:mm:ss) |
M或m | 月/日 (MM月dd日) |
Y或y | 年/月 (YYYY年/MM月) |
实例
按指定格式输出当前时间
using System;
namespace CsharpCode
{
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Now;
string S3= string.Format("Current Time is {0:d}",dt);
string S4= string.Format("Current Time is {0:D}",dt);
string S5= string.Format("Current Time is {0:t}",dt);
string S6= string.Format("Current Time is {0:T}",dt);
string S7= string.Format("Current Time is {0:f}",dt);
string S8= string.Format("Current Time is {0:F}",dt);
string S9= string.Format("Current Time is {0:g}",dt);
string S10= string.Format("Current Time is {0:G}",dt);
string S11= string.Format("Current Time is {0:m}",dt);
string S12= string.Format("Current Time is {0:y}",dt);
Console.WriteLine(S3+"\n"+S4+"\n"+S5+"\n"+S6+"\n"+S7+"\n"+S8+"\n"+S9+"\n"+S10+"\n"+S11+"\n"+S12);
}
}
}
输出
Current Time is 10/13/2018
Current Time is Saturday, October 13, 2018
Current Time is 3:39 PM
Current Time is 3:39:21 PM
Current Time is Saturday, October 13, 2018 3:39 PM
Current Time is Saturday, October 13, 2018 3:39:21 PM
Current Time is 10/13/2018 3:39 PM
Current Time is 10/13/2018 3:39:21 PM
Current Time is October 13
Current Time is October, 2018