Thursday, August 4, 2011

How to Format a DateTime in C# / ASP.NET


When I was a new developer making websites in .NET, I ended up doing some pretty screwy things to make date’s and time’s look how I wanted to. I would do things like:
DateTime thisDate = DateTime.Now;
string AMPM = String.Empty;
if(thisDate.Hour>=12) {AMPM = "PM";} else {AMPM = "AM";}
String FormattedDate = (thisDate.Hour%12).ToString() + ":" + thisDate.Minute.ToString() + " " + AMPM;
Fortunately I soon learned there were much better ways to do that. C# and Visual Basic both have a very powerful DateTime variable type, which will let you display your date/time in just about any way that you’d like  using the .ToString(“”) method. Let’s say we want to display a formatted date/time that we had stored in a variable called “ThisDate”. Here are some common ways to display your DateTime Variable:
  • ThisDate.ToString(“d”);  // “01/10/2009″
  • ThisDate.ToString(“D”);  // “Monday, 10 January 2009″
  • ThisDate.ToString(“G”);  // “01/10/2009 12:00:00″
  • ThisDate.ToString(“hh:mm tt”) // “12:00 AM”
  • ThisDate.ToString(“dddd”) // “Monday”
These are the manners that I most frequently use the ASP.NET DateTime format tool. here is a writeup on how to create your own specially formatted DateTime views.

No comments: