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);
}
Because the Unix timestamp uses an unsigned 32-bit integer, it does have a maximum of time that can be counted before the number “rolls over” into a negative number. Based on current Unix time, the rollover time will be 03:14:07 UTC on 19 January 2038.
Unix time is a date-time format used to express the number of milliseconds that have elapsed since January 1, 1970 00:00:00 (UTC). Unix time does not handle the extra seconds that occur on the extra day of leap years.
Unix timestamps are always based on UTC (otherwise known as GMT). It is illogical to think of a Unix timestamp as being in any particular time zone. Unix timestamps do not account for leap seconds.
To avoid the 2038 bug on 32 bit systems?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With