Reliable way to convert javascript label to date tuple

I want to convert javascript timestamps to erlang dates. I am using the qdate library to help me do this as it provides functions for date arithmetic as well.

Calling the to_date function first before midnight and then after midnight results in a 24 hour offset. For example: -

 qdate:to_date(Timestamp div 1000). 

 %% {2015,5,2} before midnight

 qdate:to_date(After_midnight_Timestamp div 1000) 

 %%{2015,5,2} after midnight should be 3 instead of 2

      

I did a little googling and found this in the erlang calendar docs

The time functions local_time / 0 and universal_time / 0 provided both the return date and the time in this module. The reason for this is that separate functions for date and time can result in a date / time combination that is offset by 24 hours. This happens if one of the functions is called before midnight and the other after midnight. This issue also applies to Erlang BIF date / 0 and time / 0, and their use is strongly discouraged if a reliable date / time stamp is required.

I am having trouble understanding this. Which function is from local_time/0

and universal_time/0

always gives correct results? Correctly I mean that I want the correct date to be shown after midnight. Time leave only {y,m,d}

. Don't worry about hours, minutes and seconds, or anything more beautiful.

So how can I reliably convert javascript label to date in erlang?

+3


source to share


1 answer


It looks like it was just a timezone issue :) Since I was working with javascript labels, the default timezone for javscript timestamp is my local zone which is "IST". Now when qdate sees an integer in qdate:to_date(Timestamp).

, it automatically picks the timezone UTC

for it. Relevant code on line 256 : -

raw_to_date(Unixtime) when is_integer(Unixtime) ->
    unixtime_to_date(Unixtime);

%% other clauses

      

and on line 654

unixtime_to_now(T) when is_integer(T) ->
    MegaSec = floor(T/1000000),
    Secs = T - MegaSec*1000000,
    {MegaSec,Secs,0}.

unixtime_to_date(T) ->
    Now = unixtime_to_now(T),
    calendar:now_to_datetime(Now).

      

The final key from the Erlang document itself



now_to_datetime (now) → datetime1970 ()

Types: Now = erlang: timestamp ()

This function returns Coordinated Universal Time (UTC) converted from the return value from erlang: now ().

So, the solution to this problem was to simply put the IST string with the qdate:to_date()

following: -

qdate:to_date("IST",Timestamp div 1000)

      

and it started returning the correct dates. I wasn't sure about the solution, so I ran a test with qdate:to_date(erlang:now())

and the return value was exactly 5:30 hours behind my time. So it seems like supplying the timezone string works :)

+1


source







All Articles