0

I'm developing a C# library with .NET Framework 4.5.

I need to generate this date string: 2015-12-01T07:54:20Z But now I'm generating this date string: 2015-12-01 07:54:20Z (the same that previous one but with out the T).

To generate that date I'm using this code: DateTime.Now.ToUniversalTime().ToString("u")

How can I generate the other date string with the T?

VansFannel
  • 43,504
  • 101
  • 342
  • 588

3 Answers3

4

Your format (without the trailing Z) is called the sortable format, and it has the pre-defined format specifier "s":

DateTime.UtcNow.ToString("s") + "Z"

yields

2015-12-18T09:04:58Z
Heinzi
  • 159,022
  • 53
  • 345
  • 499
2

You can write whole format DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")

or use less elegant solution ToString("u").Replace(" ","T")

HH is for 24h format and hh is for 12h format

Slasko
  • 407
  • 2
  • 8
2

Either

DateTime.UtcNow.ToString("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");

give you 2015-12-18T13:57:31.2311892-04:00

or

DateTime.UtcNow.ToString("o");

give you 2015-12-18T14:01:54.9571247Z

Turbot
  • 4,827
  • 1
  • 21
  • 27