15

I need to convert {{2012, 9, 21}, {13, 21, 11}} into timestamp().

How can I do that?

2240
  • 1,547
  • 2
  • 12
  • 30
Kirill Trofimov
  • 1,218
  • 1
  • 14
  • 26

2 Answers2

16

Corrected version:

Seconds = calendar:datetime_to_gregorian_seconds(DateTime) - 62167219200,
%% 62167219200 == calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})
{Seconds div 1000000, Seconds rem 1000000, 0}.
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • 3
    It is ok, but beware that if you are using the function erlang:now() to get a timestamp for comparison or any calculation, if will give you a time estimation starting on 1/1/1970, while calendar:datetime_to_gregorian_seconds/1 makes the evaluation from 1/1/0. So there is a difference of 719528 days... – Pascal Sep 22 '12 at 10:30
  • Oops, you are right. And since `timestamp()` is defined as starting from 1970 if possible, my answer was _not_ ok :) – Alexey Romanov Sep 22 '12 at 11:10
  • 1
    I have tried the function above: Timestamp = datetime_to_now({{2012, 9, 21}, {13, 21, 00}}) then calendar:now_to_local_time(Timestamp) returns {{2012,9,21},{17,21,0}}. My timezone is +4h. As I can understand the function returns timestamp in UTC. Right? – Kirill Trofimov Sep 24 '12 at 07:33
  • @KirillTrofimov Yes, just like timestamp returned by `now/0`. If you need local time, convert it using `calendar:local_time_to_universal_time_dst/1` first. – Alexey Romanov Sep 24 '12 at 14:06
2

You might use this

to_timestamp({{Year,Month,Day},{Hours,Minutes,Seconds}}) ->
(calendar:datetime_to_gregorian_seconds(
    {{Year,Month,Day},{Hours,Minutes,Seconds}}
) - 62167219200)*1000000;

This is part of module from this Github/Arboreus