www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - std.datetime: Getting unix time from 1970

reply Mandeep <mandeep brars.co.in> writes:
I am trying to get the number of seconds from 1970 using the 
std.datetime module.

long val = SysTime(Date(1996, 1, 1)).toUnixTime()

Shouldnt the above statement give me a Timezone independent result i.e. 
'toUnixTime'.

Also, is there a method to get seconds directly from Date and DateTime 
instead of creating SysTime.

Regards
Mandeep
Apr 25 2011
parent "Jonathan M Davis" <jmdavisProg gmx.com> writes:
 I am trying to get the number of seconds from 1970 using the
 std.datetime module.
 
 long val = SysTime(Date(1996, 1, 1)).toUnixTime()
 
 Shouldnt the above statement give me a Timezone independent result i.e.
 'toUnixTime'.
unix time is _always_ in UTC by definition. You're creating a SysTime with the Date of 1996-1-1 at midnight in your local time zone. That gets translated to whatever the appropriate time is in UTC and is kept internally as hecto-nanoseconds (100 ns) from midnight, January 1st 1 A.D. in UTC. You're then asking it to give you the unix time as a time_t, so it translates the hnsecs from midnight, January 1st 1 A.D. to seconds from midnight, January 1st 1970 A.D. The only part of all of that that relates to a time zone other than UTC is when you created the SysTime, since it needs a time zone to translate from a generic date to hnsecs in UTC, and it defaults to using LocalTime.
 Also, is there a method to get seconds directly from Date and DateTime
 instead of creating SysTime.
Date doesn't have seconds. It only has the year, month, and day. DateTime _does_ have seconds, since it holds both a Date and a TimeOfDay. It has the seconds property. This is exactly the same as with SysTime except that DateTime holds the seconds internally, so it doesn't have to do any calculations to get the seconds, and it doesn't do anything with time zones, so it doesn't have to worry about adjusting for that either. auto dt1 = DateTime(1996, 1, 1, 12, 0, 30); auto sec1 = dt1.seconds; assert(sec1 == 30); auto st = SysTime(dt1); auto sec2 = st.seconds; assert(sec1 == sec2); auto dt2 = cast(DateTime)st; assert(dt1 == dt2); - Jonathan M Davis
Apr 25 2011