26

Possible Duplicate:
datetime to string with time zone

This is one of the W3C standard date time format that I want to use in sitemap. This DateTime standard is:

Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD where TZD = time zone designator (Z or +hh:mm or -hh:mm) (eg 1997-07-16T19:20:30+01:00)

I am using the following code to get the current DateTime in that format:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:ssTZD");

But this gives: 2011-08-10T02:27:20TZD

Apparently the DateTime.Now doesn't recognize "TZD" in the parameter. Please help. How can I get the current DateTime in this format?

Community
  • 1
  • 1
Umair Khan Jadoon
  • 2,874
  • 11
  • 42
  • 63

3 Answers3

56

Use the zzz format specifier to get the timezone offset as hours and minutes. You also want to use the HH format specifier to get the hours in 24 hour format.

DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")

Result:

2011-08-09T23:49:58+02:00

Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:

DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")

Custom Date and Time Format Strings

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • how is it possible you have got 24h mod and me 12h mode? – genesis Aug 09 '11 at 21:54
  • 1
    Plus one for mentioning literal colons; people tend to forget that `:` represents the time separator of the current format provider. – Jeppe Stig Nielsen Aug 09 '15 at 22:05
  • 1
    Passing `CultureInfo.InvariantCulture` is one way to ensure that the `:` is not translated. Also it ensures the Gregorian calendar is used - as it's also possible the current culture's calendar is something else. – Matt Johnson-Pint Nov 24 '15 at 00:03
  • 1
    @genesis the capital letters "HH" shows the 24 hour format while the small letters "hh" shows the 12 hour format. – Talha Imam Mar 29 '17 at 09:21
10

use zzz instead of TZD

Example:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

Response:

2011-08-09T11:50:00:02+02:00
genesis
  • 50,477
  • 20
  • 96
  • 125
4

Try this:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

zzz is the timezone offset.

Mrchief
  • 75,126
  • 20
  • 142
  • 189