Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript. Compare UNIX timestamps

Tags:

javascript

I got two timestamps in unix format and I need to find a way to compare them and to find out which one is the newest (closest to present date).

The two timestamps are:

  • 1299925246
  • 1300526796

Is there a simple way of doing this in Javascript?

like image 520
Jonathan Clark Avatar asked Mar 19 '11 09:03

Jonathan Clark


People also ask

How to compare Unix timestamp JavaScript?

UNIX time is expressed as the number of seconds elapsed since January 1st, 1970, 00:00:00 UTC. Comparison is therefore straightforward: in your example, the second timestamp ( 1300526796 ) is the newest, because 1300526796 (March 19th, 2011, 09:26:36 UTC) is greater than 1299925246 (March 12th, 2011, 10:20:46 UTC).

How to compare epoch time in JavaScript?

Comparing Two Dates in JavaScript Another way to compare two dates is by using the built-in getTime() method. The getTime() method returns the number of milliseconds elapsed since the Unix epoch.

Can I compare timestamp?

Additionally, a TIMESTAMP WITHOUT TIME ZONE value can be compared with a TIMESTAMP WITH TIME ZONE value. All comparisons are chronological, which means the further a point in time is from January 1, 0001, the greater the value of that point in time. The time 24:00:00 compares greater than the time 00:00:00.


2 Answers

UNIX time is expressed as the number of seconds elapsed since January 1st, 1970, 00:00:00 UTC.

Comparison is therefore straightforward: in your example, the second timestamp (1300526796) is the newest, because 1300526796 (March 19th, 2011, 09:26:36 UTC) is greater than 1299925246 (March 12th, 2011, 10:20:46 UTC).

like image 161
Frédéric Hamidi Avatar answered Nov 14 '22 20:11

Frédéric Hamidi


Just encountered the same issue, but with multiple timestamps, like so:

1356036198452 
1356039026690
1356039067568
1356035166411

In my case, there could be anywhere from 1 to 100 timestamps available.

So the quickest way to get to the "newest" date (in my opinion) would be to do this:

var newestDate = Math.max(1356036198452,1356039026690,1356039067568,1356035166411);
alert(newestDate);

Hope that helps someone out there in the real world.

like image 39
Ace Avatar answered Nov 14 '22 22:11

Ace