ใช้ String.Format หรือ String Interpolation (C# 6+) กับ Standard / Custom Format Specifiers เพื่อจัดรูปแบบ DateTime
Standard Format Specifiers
| Specifier | ชื่อ | ตัวอย่าง (en-US) |
d | Short Date | 2/8/2018 |
D | Long Date | Thursday, February 8, 2018 |
f | Full Date/Time (Short Time) | Thursday, February 8, 2018 12:07 PM |
F | Full Date/Time (Long Time) | Thursday, February 8, 2018 12:07:07 PM |
g | General (Short Time) | 2/8/2018 12:07 PM |
G | General (Long Time) | 2/8/2018 12:07:07 PM |
M, m | Month/Day | February 8 |
O, o | Round-trip (ISO 8601) | 2018-02-08T12:07:07.1230000 |
R, r | RFC1123 | Thu, 08 Feb 2018 12:07:07 GMT |
s | Sortable (ISO 8601) | 2018-02-08T12:07:07 |
t | Short Time | 12:07 PM |
T | Long Time | 12:07:07 PM |
u | Universal Sortable | 2018-02-08 12:07:07Z |
U | Universal Full | Thursday, February 8, 2018 12:07:07 PM |
Y, y | Year/Month | February, 2018 |
Custom Format Specifiers
| Specifier | คำอธิบาย | ตัวอย่าง |
y | Year (1-2 digit) | 18 |
yy | Year (2 digit) | 18 |
yyy | Year (3+ digit) | 2018 |
yyyy | Year (4 digit) | 2018 |
M | Month (1-2 digit) | 2 |
MM | Month (2 digit) | 02 |
MMM | Month Abbreviated | Feb |
MMMM | Month Full Name | February |
d | Day (1-2 digit) | 8 |
dd | Day (2 digit) | 08 |
ddd | Day Abbreviated | Thu |
dddd | Day Full Name | Thursday |
h/hh | Hour (12h) | 12 / 12 |
H/HH | Hour (24h) | 12 / 12 |
m/mm | Minute | 07 |
s/ss | Second | 07 |
f..fffffff | Fraction of Second | .1 / .12 / .123 |
t/tt | AM/PM Designator | P / PM |
z/zz/zzz | Timezone 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