-1

how to convert this DateTime.Now to something like this 2018-04-07T00:00:00Z

I tried to do something like this

string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);
Ali Shawky
  • 13
  • 4
  • You can use the answers below to wrap it in a custom `JsonConverter`, so that all `DateTime`s get converted this way. – Caramiriel May 06 '18 at 20:40
  • Possible duplicate of [date format yyyy-MM-ddTHH:mm:ssZ](https://stackoverflow.com/questions/1728404/date-format-yyyy-mm-ddthhmmssz) – Lance U. Matthews May 06 '18 at 21:17
  • I'm surprised at the answer that has been accepted. It loses any daylight saving time by converting to UTC and it doesn't do what you asked because it contains apostrophes in the resulting string. Did you read/try my answer? It gives an answer using ISO8601. – Richardissimo May 11 '18 at 06:00

3 Answers3

2

You can use DateTime.Now.ToString("u").
Please read below post for more information:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

AliJP
  • 668
  • 1
  • 4
  • 16
  • The "u" format loses the fractions of a second and converts the value to a UTC (losing the local timezone and/or daylight saving offset). So although at-a-glance this might look like a good answer, I don't think it's the right one. – Richardissimo May 07 '18 at 06:40
1

You can do something like this:

string date = DateTime.Now.ToUniversalTime()
                          .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
Saadi
  • 2,211
  • 4
  • 21
  • 50
0

I suspect the answer you need is by using

string date = DateTime.Now.ToString("O");

This is called the RoundTrip kind because it is designed to preserve information through a serialization/deserialization round trip, which sounds like it might be what you're doing. And it includes the T in the middle as requested.

Richardissimo
  • 5,596
  • 2
  • 18
  • 36