13

I'm needing to convert a DateTime to a Unix timestamp. So I googled it looking for some example code

In just about all the results I see, they use double as the return for such a function, even when explicitly using floor to convert it to an integer. Unix timestamps are always integers. So what problem is there with using either long or int instead of double?

static double ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    TimeSpan diff = date - origin;
    return Math.Floor(diff.TotalSeconds);
}
mskfisher
  • 3,291
  • 4
  • 35
  • 48
Earlz
  • 62,085
  • 98
  • 303
  • 499
  • IMHO just not to validate the input date. It should return a long or an ad-hoc struct – onof Mar 05 '11 at 21:44
  • 1
    There is no reason, it is just crummy code. Cast to a long, it can't overflow. – Hans Passant Mar 05 '11 at 23:19
  • I'll add that by definition the Unix timepstamp is UTC. The method should check if the DateTime.Kind is UTC, Local, or Unspecified. At minimum if Local I would convert to UTC before performing the conversion. Optionally, if you want a Unix timestamp that is local you could add an overload or parameter to not perform the conversion to UTC. – Nate Mar 06 '11 at 01:55
  • @Nate, hmm yea true, but it doesn't matter in my case. – Earlz Mar 06 '11 at 03:14

4 Answers4

6

Usually, I would implement it with an unsigned long instead of requiring the user to round up or down and cast to an int or long. One reason someone might want a double is if a structure similar to timeval were being used such as in gettimeofday. It allows for sub-second precision...

Nate
  • 5,237
  • 7
  • 42
  • 52
4

To avoid the 2038 bug on 32 bit systems?

Jaap Versteegh
  • 761
  • 7
  • 15
1

Doubles cover more ground then any other variable in the int type.

James Mercer
  • 111
  • 2
  • 10
  • yes, but a `long` would cover thousands of years. Surely my software won't be running in a couple thousand years. – Earlz Mar 05 '11 at 23:57
  • I suppose if you had some software that needed to calculate something eons into the future or the past, it may help. That's a special case though, and one would probably use a custom data type under said scenario. – Nate Mar 06 '11 at 01:49
-2

It's not a question of "years". but of hours on a reasonable machine (s), properly linked.

But can you imagine collating the enormous storage? I have about 30TB off data and it swamps me - I spend more time cataloging than actual work.

Good luck in your endeavors

antonsachs
  • 59
  • 4