1

I would like to convert a UTC time to to the following format (IS0 8601). Eg.

2000-01-01T17:00:00-05:00

Currently I'm using UtcNow.Convert.ToString("s"), which gives me the datetime in the format

2015-12-05T08:49:14

but this skips the time part after the "-" symbol.

Can anybody help on this ?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92

1 Answers1

3

I think your format is little bit different than ISO 8601 format.

First of all, when you use any z format specifier, you always get + or - sign depends on your UTC Offset value is negative or positive.

Would be better to get your current local time zone utc offset, format it with hh\\:mm format and combine your formatted UtcNow value like;

var utcOffset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);
var formattedOffset = utcOffset.ToString("hh\\:mm");
Console.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss'-'" + formattedOffset));

Or you can use The "s" standard format specifier and format your offset part with - string literal as;

Console.WriteLine(DateTime.UtcNow.ToString("s") + utcOffset.ToString("'-'hh\\:mm"));
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364