3

I need to compare the timestamp given by my backend (which is in Perl) and the timestamp of by front-end (which is in JS), so I need to be sure that they both use the same time unit.

For JS it's easy, quoting:

A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the given date.

For Perl, the documentation about $dt->epoch() says:

Return the UTC epoch value for the datetime object. Datetimes before the start of the epoch will be returned as a negative number.

The return value from this method is always an integer.

Since the epoch does not account for leap seconds, the epoch time for 1972-12-31T23:59:60 (UTC) is exactly the same as that for 1973-01-01T00:00:00.

To me, it's not clear if the returned integer is in milliseconds or seconds (in the second case I would need to convert JS epoch in seconds or viceversa).

Which one is correct?

Community
  • 1
  • 1
justHelloWorld
  • 6,478
  • 8
  • 58
  • 138

2 Answers2

9

In the context of DateTime, "epoch" refers to Unix time, which is the number of seconds that aren't leap seconds since 1970-01-01T00:00:00Z.

$ perl -MDateTime -e'CORE::say DateTime->from_epoch( epoch => 1 )'
1970-01-01T00:00:01

$ perl -MDateTime -e'CORE::say DateTime->from_epoch( epoch => 1000 )'
1970-01-01T00:16:40

However, DateTime supports times with a resolution of nanosecond, so you could use the following to get a JavaScript timestamp.

my $js_time = $dt->epoch * 1000 + $dt->millisecond;

Of course, getting a value other than zero for the millisecond component assumes the DateTime object was created with a sufficiently precise time. That's not the case for

my $dt = DateTime->now();

because it uses time operator to obtain the current time. To get a higher-resolution timestamp, you could use the following:

use Time::HiRes qw( time );

my $dt = DateTime->from_epoch( epoch => time() );
ikegami
  • 367,544
  • 15
  • 269
  • 518
7
$ perl -MDateTime -wE 'say DateTime->new( year => 1971 )->epoch'
31536000
$ bc <<< 365*24*60*60
31536000
choroba
  • 231,213
  • 25
  • 204
  • 289