Pages

Tuesday, June 30, 2009

Formatted output of DateTime with millisecond resolution

If you want to get the DateTime output in your code with millisecond resolution, like "2009-06-30T18:49:34.797Z", you can use the below C# code.

///
/// The date time format specifier.
///

private const string DateTimeFormatSpecifier = "yyyy-MM-ddTHH\\:mm\\:ss.fffZ";

///
/// Method to obtain the current date time with millisecond resolution.
///

protected void GetDateTimeNow()
{
DateTime value = DateTime.UtcNow;

string dateTimeValueInMs = value.ToString(
DateTimeFormatSpecifier,
DateTimeFormatInfo.InvariantInfo);

Console.WriteLine(String.Format("The current date time in milliseconds is : {0}", dateTimeValueInMs));
}