131

I assume this should be pretty simple, but could not get it :(. In this format Z is time zone.
T is long time pattern
How could I get a date in this format except by using

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString("yyyy-MM-ddTHH:mm:ssZ"));

in C#

Saar
  • 8,286
  • 5
  • 30
  • 32
  • 5
    I know this question has been around for 9 years but the accepted answer of `UtcNow.ToString(s)+Z` is the wrong one. ISO8601 is supported by the [RoundTrip](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#the-round-trip-o-o-format-specifier) option `ToString("O")`. Also to point out that the accepted answer uses the UTC value of the datetime, which would always give timezone Z, rather than just using the actual datetime value, which (if Kind=Local) may contain a daylight saving timezone. Consider changing the accepted answer? – Richardissimo May 07 '18 at 06:15

10 Answers10

176

Using UTC

ISO 8601 (MSDN datetime formats)

Console.WriteLine(DateTime.UtcNow.ToString("s") + "Z");

2009-11-13T10:39:35Z

The Z is there because

If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

If you want to include an offset

int hours = TimeZoneInfo.Local.BaseUtcOffset.Hours;
string offset = string.Format("{0}{1}",((hours >0)? "+" :""),hours.ToString("00"));
string isoformat = DateTime.Now.ToString("s") + offset;
Console.WriteLine(isoformat);

Two things to note: + or - is needed after the time but obviously + doesn't show on positive numbers. According to wikipedia the offset can be in +hh format or +hh:mm. I've kept to just hours.

As far as I know, RFC1123 (HTTP date, the "u" formatter) isn't meant to give time zone offsets. All times are intended to be GMT/UTC.

Chris S
  • 64,770
  • 52
  • 221
  • 239
  • Cool. Your output doesn't include the TZ offset, though? – Neil Barnwell Nov 13 '09 at 10:39
  • I added it in - the docs say the 's' format is **based** on ISO8601 I don't think it includes the timezone. – Chris S Nov 13 '09 at 10:43
  • Oh of course, UTC doesn't have timezones. D'oh. He is asking for timezone info in his output. Maybe the DateTimeOffset is what he's looking for? – Neil Barnwell Nov 13 '09 at 10:47
  • 8
    Adding Z there manually is not good, you should use .ToString("o") because it will give you the proper output. If milliseconds are problem, they should be rounded. Adding Z manually can give incorrect result if you add it to local time, which isn't really UTC. – Tuukka Lindroos Sep 08 '15 at 18:56
94
Console.WriteLine(DateTime.UtcNow.ToString("o"));  
Console.WriteLine(DateTime.Now.ToString("o"));

Outputs:

2012-07-09T19:22:09.1440844Z  
2012-07-09T12:22:09.1440844-07:00
Rami A.
  • 10,302
  • 4
  • 44
  • 87
  • I used Console.WriteLine(DateTime.Now.ToString("o"));. Thanks – Ziggler Apr 22 '15 at 17:20
  • 5
    The accepted answer says to use format specifier "s" and append a Z on the end for UTC dates. That's all good and fine if you don't need the milliseconds, but if you want the milliseconds you have to use "o" like this answer shows. With "o", the milliseconds show up by default and the Z is already appended on the end for UTC dates. – Jim Oct 29 '15 at 15:06
  • 1
    DateTime.Now.ToString("o") Solves all kind of problems because it return the right offset with it. – Mo Zaatar May 05 '17 at 04:21
  • A possible unintended side-effect of using "o" in the format is that timestamps may sort in non-chronological order because the "o" format truncates zeroes in the milliseconds and Z sorts after 0 (zero). Consider "2020-05-21T00:13:44.52Z" and "2020-05-21T00:13:44.529Z" where the first timestamp should be before the second, but alpha-numberically, it is not. – tiwahu Jun 01 '21 at 16:27
17

"o" format is different for DateTime vs DateTimeOffset :(

DateTime.UtcNow.ToString("o") -> "2016-03-09T03:30:25.1263499Z"

DateTimeOffset.UtcNow.ToString("o") -> "2016-03-09T03:30:46.7775027+00:00"

My final answer is

DateTimeOffset.UtcDateTime.ToString("o")   //for DateTimeOffset type
DateTime.UtcNow.ToString("o")              //for DateTime type
LucasM
  • 431
  • 4
  • 11
15

In C# 6+ you can use string interpolation and make this more terse:

$"{DateTime.UtcNow:s}Z"
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
8

Single Line code for this.

var temp   =  DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");
Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
Vivek Samele
  • 340
  • 4
  • 8
7

Look here at "u" and "s" patterns. First is without 'T' separator, and the second one is without timezone suffix.

HolisticElastic
  • 937
  • 8
  • 17
7

Use:

DateTime.UtcNow.ToString("yyyy-MM-ddThh:mm:ss.fffZ")

The outcome is : 2021-05-26T10:17:38.549Z

anil shrestha
  • 2,136
  • 2
  • 12
  • 26
  • "hh" is the 12-hour format and not ISO 8601-compliant. If that were intended, you would need to insert "tt" to indicate AM/PM. The simple fix is to use "HH" which is the 24-hour format. – user1050483 Feb 10 '23 at 18:19
6

One option could be converting DateTime to ToUniversalTime() before converting to string using "o" format. For example,

var dt = DateTime.Now.ToUniversalTime();
Console.WriteLine(dt.ToString("o"));

It will output:

2016-01-31T20:16:01.9092348Z
Khalil
  • 139
  • 2
  • 1
3

It works fine with Salesforce REST API query datetime formats

DateTime now = DateTime.UtcNow;
string startDate = now.AddDays(-5).ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");   
string endDate = now.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");  
//REST service Query 
string salesforceUrl= https://csxx.salesforce.com//services/data/v33.0/sobjects/Account/updated/?start=" + startDate + "&end=" + endDate;

// https://csxx.salesforce.com/services/data/v33.0/sobjects/Account/updated/?start=2015-03-10T15:15:57Z&end=2015-03-15T15:15:57Z

It returns the results from Salesforce without any issues.

-10

You could split things up, it would require more code but would work just the way you like it:

DateTime year = DateTime.Now.Year;
DateTime month = DateTime.Now.Month;
DateTime day = DateTime.Now.Day;

ect.

finally:

Console.WriteLine(year+month+day+etc.);

This is a very bold way of handling it though...

Pieter888
  • 4,882
  • 13
  • 53
  • 74