DateTime.ToString 提供多種標準格式字符,無需組合自定義模式即可快速輸出常見日期時間格式。本文列出所有標準格式字符及其對應屬性/說明。
| 格式字符 | 關聯屬性/說明 |
|---|---|
| d | ShortDatePattern(短日期) |
| D | LongDatePattern(長日期) |
| f | 完整日期時間(長日期+短時間) |
| F | FullDateTimePattern(長日期+長時間) |
| g | 常規(短日期+短時間) |
| G | 常規(短日期+長時間) |
| m, M | MonthDayPattern |
| r, R | RFC1123Pattern |
| s | SortableDateTimePattern(基於 ISO 8601,當地時間) |
| t | ShortTimePattern(短時間) |
| T | LongTimePattern(長時間) |
| u | UniversalSortableDateTimePattern(通用時間格式) |
| U | 完整日期時間(通用時間,長日期+長時間) |
| y, Y | YearMonthPattern |
using System;
using System.Globalization;
string format = "D";
DateTime date = DateTime.Now;
Console.WriteLine(date.ToString(format, DateTimeFormatInfo.InvariantInfo));
// 輸出範例:Thursday, June 16, 2005
標準格式字符區分大小寫,且不可與自定義模式混用。若需更精細控制,請參考自定義格式字符串(下篇)。