在 C# 開發中,日期時間的處理是基礎卻又容易踩坑的環節。無論是從資料庫讀取字串轉換為 DateTime,還是依據業務需求輸出特定格式,掌握核心 API 能大幅提升開發效率。本文整理實務上最常用的日期格式化技巧,助你快速上手。
// 1. 字串轉 DateTime(自動辨識 "yyyy-MM-dd HH:mm:ss" 等常見格式)
DateTime dt = Convert.ToDateTime("2024-05-07 12:46:53");
// 2. 自訂格式輸出:yyyy-MM-dd HH:mm:ss(24 小時制)
string formatted = dt.ToString("yyyy-MM-dd HH:mm:ss");
// 結果:"2024-05-07 12:46:53"
// 3. 僅取日期部分(短日期格式,依系統文化特性而異)
string shortDate = dt.ToShortDateString();
// 例如:"2024/05/07" 或 "2024-05-07"
// 4. 進階:指定文化特性與格式
string custom = dt.ToString("yyyy年MM月dd日 HH時mm分", new CultureInfo("zh-TW"));
// 結果:"2024年05月07日 12時46分"
| 代碼 | 說明 | 範例輸出 |
|---|---|---|
| yyyy | 四位數年份 | 2024 |
| MM | 兩位數月份 (01-12) | 05 |
| dd | 兩位數日期 (01-31) | 07 |
| HH | 24 小時制小時 (00-23) | 12 |
| mm | 分鐘 (00-59) | 46 |
| ss | 秒數 (00-59) | 53 |
| tt | AM/PM 標記 | PM |
// 假設 dr 為 SqlDataReader,欄位名為 "CreateTime"
if (dr["CreateTime"] != DBNull.Value)
{
DateTime createTime = Convert.ToDateTime(dr["CreateTime"]);
// 依需求輸出格式
string display = createTime.ToString("yyyy/MM/dd HH:mm");
Console.WriteLine(display);
}
Convert.ToDateTime 依賴執行緒目前文化特性,跨地區部署時建議改用 DateTime.ParseExact 指定格式。DBNull.Value。CultureInfo 物件有開銷,可快取靜態實例。掌握 Convert.ToDateTime 快速轉換、ToString(format) 彈性輸出,再搭配 ParseExact 嚴格驗證,即可應付 90% 的日期格式化需求。記得根據部署環境設定合適的文化特性,避免格式誤解導致的 Bug。