Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - compare dates in different formats

I have 2 dates which I need to compare to see if one is greater than the other but they are in different formats and I'm not sure of the best way to compare the 2.

The formats are:

1381308375118 (this is var futureDate)

which is created by

var today = new Date(); today.setHours(0, 0, 0, 0); var futureDate = new Date().setDate(today.getDate() + 56); //56 days in the future...

And the other format is

2013/08/26

Any ideas how I can compare the 2?

like image 542
Tom Avatar asked Aug 14 '13 08:08

Tom


People also ask

Can you compare JavaScript dates?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

Can we compare dates in string format?

In this very case you can just compare strings date1. compareTo(date2) . EDIT: However, the proper way is to use SimpleDateFormat : DateFormat f = new SimpleDateFormat("yyyy-mm-dd"); Date d1 = f.


1 Answers

Without using a 3rd party library, you can create new Date objects using both those formats, retrieve the number of milliseconds (since midnight Jan 1, 1970) using getTime() and then simply use >:

new Date("2013/08/26").getTime() > new Date(1381308375118).getTime()
like image 177
Castrohenge Avatar answered Nov 12 '22 12:11

Castrohenge