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 ?

4
  • Is - between your time part and offset part means just - separator or it represents negative offset? Commented Dec 5, 2015 at 10:54
  • its just a - seperator Commented Dec 5, 2015 at 10:56
  • You say you have a UTC time but you want it to display a UTC offset, which by definition is zero. Commented Dec 5, 2015 at 12:48
  • If you don't have a UTC time, the round trip ("o") specifier will give something like "2009-06-15T13:45:30.0000000-07:00" Commented Dec 5, 2015 at 12:50

1 Answer 1

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.