SoFunction
Updated on 2025-03-07

Detailed explanation of the example of C# implementing formatted output of date and time

DateTime is placed under the System namespace, and it does not have to use it directly in the top-level statement.

Single letter formatting

The most commonly used attribute of DateTime is Now, which represents the current time and its data type is also DateTime. But generally speaking, Now contains a lot of content. The more appropriate usage is to format and output it through some keywords. These keywords can be single letters, as shown in the following example

string[] formatLst = new string[] { "d", "D", "f", "F", "g", "G", "t", "T", "u", "U", "m", "M", "r", "R", "y", "Y", "o", "O", "s" };
foreach (var item in formatLst)
{
    var now = ;
    ($"{item}|{(item)}");
}
Logo Output
2023/3/3 15:41:59
d 2023/3/3
D March 3, 2023
f March 3, 2023 15:41
F March 3, 2023 15:41:00
g 2023/3/3 15:41
G 2023/3/3 15:41:00
t 15:41
T 15:41:00
u 2023-03-03 15:41:00Z
U March 3, 2023 7:41:00
m March 3
M March 3
r Fri, 03 Mar 2023 15:41:00 GMT
R Fri, 03 Mar 2023 15:41:00 GMT
y March 2023
Y March 2023
o 2023-03-03T15:41:00.4768044+08:00
O 2023-03-03T15:41:00.4769105+08:00
s 2023-03-03T15:41:00

in,UIndicates the long date and time of the prime meridian.

Custom formatting

ToStringMore complex formatting methods are also overloaded

string[] fmtLst = new string[] { "yy", "yyyy", "MM", "dd", "ddd", "dddd", "hh", "HH", "mm", "ss", "ff", "fff", "ffff"};
foreach (var item in fmtLst)
{
    var now = ;
    ($"{item}|{(item)}");
}
Format Output illustrate
yy 23 Two digits after the year
yyyy 2023 4 years
MM 03 Two months
dd 03 Number of days
ddd Friday
dddd Friday
hh 03 Number of hours in a 12-hour system
HH 15 24-hour hours
mm 45 Minutes
ss 51 Number of seconds
ff 15 The first 2 digits in milliseconds
fff 156 The first 3 digits in milliseconds
ffff 1567 The first 4 digits in milliseconds

The above keywords for a single year, month, day, hour, minute, and second can be freely combined by inserting other symbols, for example

var dt1 = ("yyyy-MM-dd HH:mm:");
var dt2 = ("yyyy/MM/dd HH:mm:ss");
var dt3 = ("Yyyy MM month ddddd");
(dt1);
(dt2);
(dt3);

The command line output is

2023-03-03 15:50:20.8885
2023/03/03 15:50:20
Friday, March 3, 2023

This is the end of this article about the detailed explanation of the formatting output of C# for date and time. For more related C# date and time formatting output content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!