0

I tried How can I convert a DateTime to the number of seconds since 1970? with

    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    DateTime date = DateTime.Parse(@"28/05/12 01:30");
    TimeSpan diff = date.ToUniversalTime() - origin;
    Console.WriteLine( (Math.Floor(diff.TotalSeconds)).ToString());

Output = 1338161400

It is wrong compared to http://www.mbari.org/staff/rich/utccalc.htm 1338168600

Why ?

Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487

2 Answers2

2

This is most likely from a time zone difference. If you store the values in temp variables and look, you will probably see that the ToUniversalTime modifies the original value appropriately:

        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        DateTime date = DateTime.Parse(@"05/28/2012 01:30:00");
        date = date.ToUniversalTime();

In my case, when I look at date after setting it to UniversalTime I see the time as 5:30:00 since I am on the east coast.

So, to force this to be as you expected, I just shifted my time to actually be GMT (change my date by 4 hours:

        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        DateTime date = DateTime.Parse(@"05/27/2012 9:30:00 pm");
        date = date.ToUniversalTime();
        TimeSpan diff = date - origin;
        Console.WriteLine((Math.Floor(diff.TotalSeconds)).ToString());

This yields: 1338168600

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
0

The .NET DateTime-related classes are supposed to Just Work. They often do, but you have to pay attention to the details if you're working with anything but local time. (This is not a .NET-specific problem - time zones, and especially DST, often cause major headaches.) The following snippet should produce the proper output regardless of your locale:

DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime date = DateTime.Parse(@"28/05/12 01:30", null, System.Globalization.DateTimeStyles.AssumeUniversal);
TimeSpan diff = date.ToUniversalTime() - origin;
Console.WriteLine((Math.Floor(diff.TotalSeconds)).ToString());

Note that for both input dates, one needs to specify explicitly that the date should be seen as a UTC date and not as a local date. The ToUniversalTime() call seems superfluous, but it is necessary to produce the proper difference. This seems to be an oversight in the implementation of the minus operator.

See also Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo on MSDN.

MvanGeest
  • 9,536
  • 4
  • 41
  • 41