Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

C# DateTime 格式化大全:標準/自定義格式字串、GMT/RFC1123、常用 ToString 模式速查

編輯:Linux 教學

一鍵產生 GMT (RFC1123) 格式

DateTime now = DateTime.Now;
string gmt = now.ToString("r");  // 或 "R"
// 輸出:Wed, 22 Jul 2009 16:24:33 GMT

"r"/"R" 對應 RFC1123Pattern,固定輸出 GMT,不受當地文化特性影響。

標準格式字元對照表

格式說明範例輸出
d短日期2009/7/22
D長日期2009年7月22日
f完整日期時間(長日期+短時間)2009年7月22日 16:24
F完整日期時間(長日期+長時間)2009年7月22日 16:24:33
g一般(短日期+短時間)2009/7/22 16:24
G一般(短日期+長時間)2009/7/22 16:24:33
m/M月日7月22日
r/RRFC1123 (GMT)Wed, 22 Jul 2009 16:24:33 GMT
s可排序 (ISO 8601, 本地)2009-07-22T16:24:33
t短時間16:24
T長時間16:24:33
u通用可排序 (UTC, ISO 8601)2009-07-22 16:24:33Z
U完整日期時間 (UTC)2009年7月22日 16:24:33
y/Y年月2009年7月

自定義格式字元(區分大小寫)

字元含義範例
y年(無前導0)9
yy年(兩位)09
yyyy年(四位)2009
M月(無前導0)7
MM月(兩位)07
MMM月縮寫Jul / 七月
MMMM月全名July / 七月
d日(無前導0)22
dd日(兩位)22
ddd星期縮寫Wed / 三
dddd星期全名Wednesday / 星期三
h12制時(無前導0)4
hh12制時(兩位)04
H24制時(無前導0)16
HH24制時(兩位)16
m分(無前導0)24
mm分(兩位)24
s秒(無前導0)33
ss秒(兩位)33
f~ffffff秒小數位 1~7 位.3 / .33 / .333
tAM/PM 首字P
ttAM/PM 全寫PM
z時區偏移(小時)+8
zz時區偏移(兩位小時)+08
zzz時區偏移(時:分)+08:00
:時間分隔符:
/日期分隔符/

常用組合範例

// 2009-07-22 16:24:33
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

// 2009年07月
DateTime.Now.ToString("yyyy年MM月", CultureInfo.InvariantCulture)

// 20090722162433 (檔案命名)
DateTime.Now.ToString("yyyyMMddHHmmss")

// 只取年月
DataBinder.Eval(item, "Date", "{0:yyyy-M}")

ASP.NET 資料繫結格式化


// 或 Code-behind
e.Item.Cells[0].Text = Convert.ToDateTime(e.Item.Cells[0].Text).ToShortDateString();
Copyright © Windows教程網 All Rights Reserved