[c#] date format yyyy-MM-ddTHH:mm:ssZ

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#

This question is related to c#

The answer is


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.


"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

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

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...


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


Single Line code for this.

var temp   =  DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");

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

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

$"{DateTime.UtcNow:s}Z"