How to properly parse DateTime string

I've got input date time strings which look like this: 2015-01-28 17:55:43. The problem is that they are in UTC+8 (or some other shift). I need those strings parsed and processed properly into UTC, regardless of the timezone where the software runs. My problem is that DateTime.Parse returns local time, not UTC time, and I don't see a way to specify shift when parsing the string. My current solution to this looks something like this:

add.LastUpdatedTime = new DateTime((DateTime.Parse(text) - new TimeSpan(0, 8, 0, 0)).Ticks,DateTimeKind.Utc);

This is ugly, and I'm not sure that it will work well in all circumstances.

Is there a better way of doing this?

Jon Skeet
people
quotationmark

Given that you have a local time and an offset, I'd suggest representing that in DateTimeOffset. So:

DateTime localTime = DateTime.ParseExact(...);
DateTimeOffset offsetTime = new DateTimeOffset(localTime, offset);

Then you still know the local time, but you can get the UTC equivalent when you want it. Basically it preserves all the information you have.

As an alternative, you could use Noda Time which represents the same information in OffsetDateTime. You'd use a LocalDateTimePattern to parse the value to a LocalDateTime, then use the WithOffset method to convert to an appropriate OffsetDateTime.

people

See more on this question at Stackoverflow