[erlang-questions] When the heck is now -

Joe Armstrong erlang@REDACTED
Fri Oct 21 10:30:27 CEST 2016


When is now?

I want the raw uncorrected system time - I assume this is

   erlang:system_time()

Seems to return the raw system clock in nanosconds past Epoch

I want to convert this to a printable local time that agrees with my
wristwatch (ie what the man on the Clapham omnibus might call the
time)

So I'd like to convert this to
Year,Month,Day,Hour,Min,Sec,Fraction of sec

There seems to be no function to do this (strange since,
this seems to me to be a common thing one might want to do).

In the old days I'd write:

t1() ->
    T1 = erlang:timestamp(),
    calendar:now_to_local_time(T1).

This works fine:

 > t1:t1().
  {{2016,10,21},{9,59,59}}

After scratching my head and reading the manual pages
I ended up with this:

t2() ->
    T1 = erlang:system_time(),
    system_time_to_ymdhms(T1).

system_time_to_ymdhms(T) ->
    S = erlang:convert_time_unit(T, native, seconds),
    {Days, X} = calendar:seconds_to_daystime(S),
    {Y,Month,Day} = calendar:gregorian_days_to_date(Days),
    {{Y+1970,Month,Day}, X}.

Now stunningly obvious - and wrong by 2 hours
(The erlang manual page is WRONG - it's seconds (plural) not second)

   > t1:t1().
   {{2016,10,21},{10,18,32}}
   > t1:t2().
   {{2016,10,21},{8,18,34}}

The erlang manual page also says

QUOTE
The erlang:timestamp() BIF is equivalent to:

timestamp() ->
   ErlangSystemTime = erlang:system_time(microsecond),
   MegaSecs = ErlangSystemTime div 1000000000000,
   Secs = ErlangSystemTime div 1000000 - MegaSecs*1000000,
   MicroSecs = ErlangSystemTime rem 1000000,
   {MegaSecs, Secs, MicroSecs}.


Which is totally incorrect since it crashes

t3() ->
    T1 = timestamp(),
    calendar:now_to_local_time(T1).

timestamp() ->
    ErlangSystemTime = erlang:system_time(microsecond),
    MegaSecs = ErlangSystemTime div 1000000000000,
    Secs = ErlangSystemTime div 1000000 - MegaSecs*1000000,
    MicroSecs = ErlangSystemTime rem 1000000,
    {MegaSecs, Secs, MicroSecs}.

> t1:t3().
** exception error: bad argument
     in function  erlang:system_time/1
        called as erlang:system_time(microsecond)
     in call from t1:timestamp/0 (t1.erl, line 26)
     in call from t1:t3/0 (t1.erl, line 22)

At which point I'm flummoxed - the erlang manual page is totally wrong
in several places. The routines in calendar are not in phase with the
changes in time routine.

And I still can't convert erlang:system_time() to my local time
since it's two hour wrong

/Joe



More information about the erlang-questions mailing list