[erlang-questions] Working with dates.

Per Hedeland per@REDACTED
Mon Jul 16 11:58:47 CEST 2007


"Ben Hood" <0x6e6562@REDACTED> wrote:
>
>-define(MegaSeconds, 1000000000).
>-define(Seconds, 1000).
>-define(MicroSeconds, 1000).

Maybe those should rather be

-define(MilliSecondsPerMegaSecond, 1000000000).
-define(MilliSecondsPerSecond, 1000).
-define(MicroSecondsPerMilliSecond, 1000).

?:-)

>-define(UnixEpoch, 62167219200).

(I.e. the value returned by
calendar:datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}}).)

>encode_timestamp({MegaSecs, Secs, MicroSecs}) ->
>    MegaSecs * ?MegaSeconds + Secs * ?Seconds + MicroSecs / ?MicroSeconds.

Well, this turns what is apparently an erlang:now() value into
milliseconds as a floating-point number - I don't know of any Unix
timestamps that are expressed as milliseconds, whether floating-point or
integer... To get a time() timestamp, it would just be

encode_timestamp({MegaSecs, Secs, _MicroSecs}) ->
    MegaSecs * 1000000 + Secs.

(And if you want integer milliseconds, use 'div' instead of '/'.)

>encode_localtime(DateTime={{Year,Month,Day},{Hour,Min,Sec}}) ->
>    [Universal] = calendar:local_time_to_universal_time_dst(DateTime),
>    Seconds = calendar:datetime_to_gregorian_seconds(Universal),
>    (Seconds - ?UnixEpoch) * 1000.

This will be integer milliseconds - to get time() stamp, just drop the
'* 1000'.

--Per Hedeland



More information about the erlang-questions mailing list