Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

String Format สำหรับ DateTime ใน C#

ใช้ String.Format หรือ String Interpolation (C# 6+) กับ Standard / Custom Format Specifiers เพื่อจัดรูปแบบ DateTime

Standard Format Specifiers

Specifierชื่อตัวอย่าง (en-US)
dShort Date2/8/2018
DLong DateThursday, February 8, 2018
fFull Date/Time (Short Time)Thursday, February 8, 2018 12:07 PM
FFull Date/Time (Long Time)Thursday, February 8, 2018 12:07:07 PM
gGeneral (Short Time)2/8/2018 12:07 PM
GGeneral (Long Time)2/8/2018 12:07:07 PM
M, mMonth/DayFebruary 8
O, oRound-trip (ISO 8601)2018-02-08T12:07:07.1230000
R, rRFC1123Thu, 08 Feb 2018 12:07:07 GMT
sSortable (ISO 8601)2018-02-08T12:07:07
tShort Time12:07 PM
TLong Time12:07:07 PM
uUniversal Sortable2018-02-08 12:07:07Z
UUniversal FullThursday, February 8, 2018 12:07:07 PM
Y, yYear/MonthFebruary, 2018

Custom Format Specifiers

Specifierคำอธิบายตัวอย่าง
yYear (1-2 digit)18
yyYear (2 digit)18
yyyYear (3+ digit)2018
yyyyYear (4 digit)2018
MMonth (1-2 digit)2
MMMonth (2 digit)02
MMMMonth AbbreviatedFeb
MMMMMonth Full NameFebruary
dDay (1-2 digit)8
ddDay (2 digit)08
dddDay AbbreviatedThu
ddddDay Full NameThursday
h/hhHour (12h)12 / 12
H/HHHour (24h)12 / 12
m/mmMinute07
s/ssSecond07
f..fffffffFraction of Second.1 / .12 / .123
t/ttAM/PM DesignatorP / PM
z/zz/zzzTimezone Offset+7 / +07 / +07:00

ตัวอย่างโค้ด

using System;

class Demo {
    static void Main() {
        DateTime d = new DateTime(2018, 2, 8, 12, 7, 7, 123);
        
        // String.Format (Classic)
        Console.WriteLine(String.Format("{0:d}", d));           // 2/8/2018
        Console.WriteLine(String.Format("{0:D}", d));           // Thursday, February 8, 2018
        Console.WriteLine(String.Format("{0:yyyy-MM-dd}", d));  // 2018-02-08
        Console.WriteLine(String.Format("{0:HH:mm:ss}", d));    // 12:07:07
        Console.WriteLine(String.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", d)); // 2018-02-08 12:07:07.123
        
        // String Interpolation (Modern, แนะนำ)
        Console.WriteLine($"Short Date: {d:d}");
        Console.WriteLine($"ISO 8601: {d:o}");
        Console.WriteLine($"Custom: {d:yyyy-MM-dd HH:mm:ss}");
        Console.WriteLine($"Thai: {d:dd MMMM yyyy, HH:mm}"); // 08 February 2018, 12:07
        
        // Culture-Specific
        var thaiCulture = new System.Globalization.CultureInfo("th-TH");
        Console.WriteLine(d.ToString("D", thaiCulture)); // 8 กุมภาพันธ์ 2561
        
        Console.ReadKey();
    }
}

Best Practices

  • ใช้ String Interpolation ($"") แทน String.Format — อ่านง่าย เร็วกว่า Type-Safe
  • ใช้ Standard Formats (d, D, g, G, o, s) เพื่อความเข้ากันได้
  • ใช้ CultureInfo เมื่อแสดงผลให้ User (Thai, en-US, ja-JP ฯลฯ)
  • เก็บ DateTime เป็น UTC ใน Database — Format ตอนแสดงผลเท่านั้น
  • DateTime.ToString("o") หรือ "s" สำหรับ Serialization/Logs/API