0

When writing DateTime values to a text file, I have to make sure the used timezone is always UTC +01:00. The format is then yyyy-MM-ddTHH:mm:sszzz, with the zzz part always equaling +01:00. This means that, in case the DateTime value is not in UTC +01:00, a conversion needs to happen before writing the output.

What would be the best way to go about this?

Lee White
  • 3,649
  • 8
  • 37
  • 62
  • 2
    What *do* you know about the `DateTime` in question? If you don't know its offset, you can't represent the instant at a specific offset... – Jon Skeet Jun 21 '17 at 05:51

2 Answers2

4

From the documentation:

With DateTime values, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. It does not reflect the value of an instance's System.DateTime.Kind property. For this reason, the "zzz" format specifier is not recommended for use with DateTime values.

Instead, either use DateTimeOffset values (in which "zzz" does what you think it should), or if you continue to use DateTime values then use the "K" specifier.

For example, on my computer (which is in the US Pacific time zone):

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz")          // "2017-06-21T14:57:17-07:00"
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssK")            // "2017-06-21T14:57:17Z"
DateTimeOffset.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz")    // "2017-06-21T14:57:17+00:00"
  • On line 1, even though the time is the UTC time, the offset is incorrectly showing local time.
  • On line 2, the K specifier picks up on the UTC kind and properly gives a Z in the result.
  • On line 3, the zero offset is properly conveyed by the zzz specifier.

Related: https://stackoverflow.com/a/31223893/634824

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
0

Using:

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:sszzz") 

Will result in an error. Please try this instead:

DateTime.**Now**.ToString("yyyy-MM-ddTHH:mm:sszzz") 
Lae
  • 832
  • 1
  • 13
  • 34