3

Possible Duplicate:
In C#, given a DateTime object, how do I get a ISO 8601 date in string format?

I've a variable with type DateTime in my C# code. How do I convert this to "Z" format?

Thanks.

Community
  • 1
  • 1
Jimmy
  • 2,106
  • 12
  • 39
  • 53
  • 7
    Please link to what `Z format` looks like. What have you tried? What are you stuck on? – Oded Feb 06 '12 at 17:02
  • 1
    I have to vote this question down. The author needs to give MORE details about the problem they are having, they need to explain ANY term they use, assume we know nothing. – Security Hound Feb 06 '12 at 17:06
  • your description requires anyone trying to help to google search to understand your question. This is something you should do yourself and clarify for the people trying to help you. – deltree Feb 06 '12 at 17:07
  • 1
    I assume [Where's the DateTime 'Z' format specifier?](http://stackoverflow.com/q/833102/704402) covers most of what you are looking to do. – Adam S Feb 06 '12 at 17:07
  • @deltree: Although I didn't have to google to answer I will admit I have no idea if I've answered the right question. ;-) – Chris Feb 06 '12 at 17:09
  • 2
    @All,apologies for keeping the question not clear enough.Will keep this in mind while posting questions next time. – Jimmy Feb 10 '12 at 16:24
  • I found this question by googling "z", so I disagree with the earlier comments. At least the duplicate question helped me. – Savage Mar 30 '16 at 13:13

4 Answers4

17

Do you mean converting to a string time/date like 2009-06-15 20:45:30Z? If so then try:

mydate.ToUniversalTime().ToString("u");

See http://msdn.microsoft.com/en-us/library/az4se3k1.aspx for info on Standard Date and Time format strings. In particular read the entry on using the "Universal Sortable ("u") Format Specifier" whcih explains why I have the ToUniversalTime call in there.

Chris
  • 27,210
  • 6
  • 71
  • 92
4

If you mean the universal sortable date/time pattern:

string formatted = theDate.ToString("u");

Example result:

2009-06-15 20:45:30Z
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    What a coincidence that we both used the exact same date and time for our example? ;-) – Chris Feb 06 '12 at 17:07
2

Based on a quick search it seems to me that you simply mean UTC time, in which case you can use the ToUniversalTime method of DateTime, and when displaying as a string append "Z" to the end, or use the Universal Format Specifier when calling ToString, or you could construct it using a number of format specifiers in the correct order.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
2

I guess your format is ISO 8601: DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")

Maybe a duplicate of this topic: Given a DateTime object, how do I get an ISO 8601 date in string format?

Community
  • 1
  • 1
Redger
  • 573
  • 3
  • 11