使用 DateTime.ToString("format") 或 string.Format 套用自訂格式規範:
DateTime dt = DateTime.Now;
Console.WriteLine(string.Format("Default format: {0}", dt.ToString()));
Console.WriteLine(dt.ToString("dddd dd MMMM, yyyy g"));
Console.WriteLine(string.Format("Custom Format 1: {0:MM/dd/yy hh:mm:sstt}", dt));
Console.WriteLine(string.Format("Custom Format 2: {0:hh:mm:sstt G\\MT zz}", dt));
輸出範例:
Default format: 9/24/2005 12:59:49 PM
Saturday 24 September, 2005 A.D.
Custom Format 1: 09/24/05 12:59:49PM
Custom Format 2: 12:59:49PM GMT -06
| 規範 | 說明 |
|---|---|
| 0 | 零佔位符 |
| # | 數字佔位符 |
| . | 小數點 |
| , | 千分位分隔符 |
| % | 百分比 (值乘 100) |
| E/E0 | 科學標記法 |
| ;"XX" | 字面字串 |
| ; | 區段分隔符 (正數;負數;零值) |
double dVal = 59.99, dNeg = -569.99, zeroVal = 0.0, pct = 0.23;
string formatString = "{0:$#,###0.00;($#,###0.00);nuttin}";
Console.WriteLine(string.Format(formatString, dVal)); // $59.99
Console.WriteLine(string.Format(formatString, dNeg)); // ($569.99)
Console.WriteLine(string.Format(formatString, zeroVal)); // nuttin
Console.WriteLine(pct.ToString("00%")); // 23%
三區段格式:第一區段套用正數、第二區段套用負數 (常用括號)、第三區段套用零值。