In the few years that I have been a software developer, I have work with plenty of different programming languages. The first thing that causes you headaches in all of those languages are dates and how to work with them. In this little tutorial, I would like to show you how to work with dates in C# .NET 2.0.
String to DateTime
MyString = "1999-09-01 21:34 PM";
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
DateTime to String
MyDateTime = new DateTime(1999, 09, 01, 21, 34, 00);
MyString = MyDateTime.ToString("yyyy-MM-dd HH:mm tt");
Format String For Dates
string is your most important key. In most of my projects, I make it a constant and then refer to the constant value in my code.
The following is the most commonly used format characters:
d - Numeric day of the month without a leading zero.
dd - Numeric day of the month with a leading zero.
ddd - Abbreviated name of the day of the week.
dddd - Full name of the day of the week.
Fraction of a second. The more Fs the higher the precision.
h - 12 Hour clock, no leading zero.
hh - 12 Hour clock with leading zero.
H - 24 Hour clock, no leading zero.
HH - 24 Hour clock with leading zero.
m - Minutes with no leading zero.
mm - Minutes with leading zero.
M - Numeric month with no leading zero.
MM - Numeric month with a leading zero.
MMM - Abbreviated name of month.
MMMM - Full month name.
s - Seconds with no leading zero.
ss - Seconds with leading zero.
t - AM/PM but only the first letter.
tt - AM/PM ( a.m. / p.m.)
y - Year with out century and leading zero.
yy - Year with out century, with leading zero.
yyyy - Year with century.
zz - Time zone off set with +/-.
I hope that this helped a bit, even if it is only as a reference to create new format
strings. (Always handy!!! )
For more information, please visit my site.