cs0815
cs0815

Reputation: 17428

UTC time transformation

I am trying to consume a web service which requires dates in UTC. So I found:

private static string GetDate(DateTime DateTime)
{
    DateTime UtcDateTime = TimeZoneInfo.ConvertTimeToUtc(DateTime);
    return XmlConvert.ToString(UtcDateTime, XmlDateTimeSerializationMode.Utc);
}

If I do:

DateTime DT1 = new DateTime(2012, 3, 25);
DateTime DT2 = new DateTime(2012, 3, 26);
string s1 = GetDate(DT1);
string s2 = GetDate(DT2);

s1 contains:

2012-03-25T00:00:00Z

and s2 contains:

2012-03-25T23:00:00Z

Why does s2 not contain:

2012-03-26T00:00:00Z

? Thanks.

Upvotes: 0

Views: 120

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503889

The London time zone had a daylight saving transition on March 25th at 1am (local time), moving from UTC+0 to UTC+1. So local midnight on March 26th in the UK was exactly 2012-03-25 23:00:00 in UTC. That's almost certainly the cause of the problem.

You should work out what you really, really want the values to represent. Unfortunately DateTime isn't very good on helping you out here in terms of clarity. You may want to consider using my Noda Time library - or if you don't, at least document your code in similar concepts. (It sounds like you're trying to transform a LocalDate into an Instant, and in order to do that, you need to work out which time zone you really mean.)

It's entirely possible that you may be able to get away with:

DateTime DT1 = new DateTime(2012, 3, 25, 0, 0, 0, DateTimeKind.Utc);
DateTime DT2 = new DateTime(2012, 3, 26, 0, 0, 0, DateTimeKind.Utc);

Upvotes: 3

Related Questions