Saturday, September 10, 2011

Convert DateTime values to W3C DateTime format in C#

ConvertDateToW3CTime() function takes a C# DateTime value and converts it to a W3C formatted date/time value.
The function works by first converting the date/time parameter to a UTC (Coordinated Universal Time) value and formatting it. It then appends the UTC offset time to the previously formatted string.

The T placed between the date and time simply indicates that the numbers following it are Time values. The UTC offset can be one 3 states, zero e.g. there is not difference in time between the UTC value and the local value. A zero value is identified by simply appending the letter Z to the end of the formatted datetime value. If the offset time is greater than 0 then it is preceded with a + sign, e.g. 2 hours and 30 minutes over the UTC time would be written as +02:30. If the offset is less than the UTC value then it is preceded with a sign e.g. -01:00.

/// <summary>
/// Converts a datetime value to w3c format
/// </summary>
/// <param name="date"></param>
/// <returns></returns>
public static string ConvertDateToW3CTime(DateTime date)
//Get the utc offset from the date value
var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(date);
string w3CTime = date.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss");
//append the offset e.g. z=0, add 1 hour is +01:00
w3CTime += utcOffset == TimeSpan.Zero ? "Z" :
String.Format("{0}{1:00}:{2:00}", (utcOffset > TimeSpan.Zero ? "+" : "-")
, utcOffset.Hours, utcOffset.Minutes);

return w3CTime;

Here is an example, how to use it

//Output 2011-10-17T19:10:48+01:00