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. There’s a blogger named Kathy Kam that has a great extended writeup on how to create your own specially formatted DateTime views.

Comments

  1. I prefer
    String.Format({0:d}, ThisDate);

  2. those are some good examples, but there are a few much easier ones to remember

    ToShortTimeString will give you the time in 12 hour format without date
    ToLongDateString will give you ex: January 10, 2009

    im guessing there are a few others like this, but these are the ones i have used

Speak Your Mind

*