|
[edit] C# DateTime Custom Formats
Not only does C# have the ability to display built-in DateTime formats it can also display custom formats using DateTime format components. A component is a string that represents a certain part a date. For example, M represents a month number (1-12) and H represents an hour in 24 hour format. Refer to the DateTime format list below.
|
Format
Character |
Display |
Description |
|
d |
1 |
day of the month |
|
dd |
01 |
day of the month |
|
ddd |
Sun |
day of the week |
|
dddd |
Sunday |
day of the week |
|
MM |
04 |
Month |
|
MMM |
Apr |
Month abbreviation |
|
MMMM |
April |
Month spelled out |
|
y |
7 |
Last digit of the year |
|
yy |
07 |
Last two digits of the year |
|
yyyy |
2007 |
Full year from (0001-9999) |
|
gg |
A.D. |
Era |
|
H |
2 |
Hour(12 hour format) no zero in front |
|
Hh |
02 |
Two Digit hour (12 hour format). Zero in front |
|
HH |
14 |
Hour (24 hour format) |
|
m |
5 |
minute with no zero in front |
|
mm |
05 |
minute with zero in front |
|
s |
9 |
second with no zero in front |
|
ss |
09 |
second with zero in front |
|
t |
AM/PM |
|
|
tt |
A/P |
A = AM, P = PM |
|
z |
-1 |
timezone offset |
|
zz |
-01 |
timezone offset |
|
zzz |
-01:00 |
timezone offset |
[edit] C# DateTime Examples
It is not required to use a format parameter in the ToString() method. It has a default constructor and will still print a default date format even if there is has not been a format specified. Also, you can combine different Datetime format component characters and use it different dilimeters symbols(,[]/-:).
Syntax:
object.ToString("<format component>");
[edit] Example 1:
This code will simply print the day of the week.
using System;
class Program
{
static void Main()
{
DateTime date = DateTime.Now;
Console.WriteLine(date.ToString("dddd"));
Console.Read();
}
}
[edit] Example 2:
This one prints two different styles of the date
using System;
class Program
{
static void Main()
{
DateTime date = DateTime.Now;
Console.WriteLine(date.ToString("dddd, MMMM dd yyyy"));
Console.WriteLine(date.ToString("MMddyyyy"));
Console.Read();
}
}
Run both examples in your compiler and experiment with DateTime formats.
|