Javascript - compare dates in different formats

I have two dates that I need to compare to see if they are larger than the others, but they are in different formats, and I'm not sure about the best way to compare 2.

Formats:

1381308375118 (this is var futureDate)

which is created

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

And another format

2013/08/26

Any ideas how I can compare 2?

+5
source share
5 answers

Without using a third-party library, you can create new Date objects using both of these formats, get the number of milliseconds (from midnight January 1, 1970) using getTime() , and then simply use > :

 new Date("2013/08/26").getTime() > new Date(1381308375118).getTime() 
+10
source

I highly recommend using datejs library .

Thus, this can be written on one line:

 Date.today().isAfter(Date.parse('2013/08/26')) 
+2
source

I would like to make sure that I am comparing the "date" element of each format and excluding any time element. Then, when both dates are converted to milliseconds, just compare the values. You could do something like this. If the dates are equal, they return 0 if the first date is less than the second and then returns -1, otherwise returns 1.

Javascript

 function compareDates(milliSeconds, dateString) { var year, month, day, tempDate1, tempDate2, parts; tempDate1 = new Date(milliSeconds); year = tempDate1.getFullYear(); month = tempDate1.getDate(); day = tempDate1.getDay(); tempDate1 = new Date(year, month, day).getTime(); parts = dateString.split("/"); tempDate2 = new Date(parts[0], parts[1] - 1, parts[2]).getTime(); if (tempDate1 === tempDate2) { return 0; } if (tempDate1 < tempDate2) { return -1; } return 1; } var format1 = 1381308375118, format2 = "2013/08/26"; console.log(compareDates(format1, format2)); 

Jsfiddle on

+1
source

Perhaps you can use Date.parse("2013/08/26") and compare with the previous

0
source

Follow these steps to compare dates.

Each of your dates should go through a Date object i.e. new Date(yourDate) . Now the dates will have the same format and they will be comparable

 let date1 = new Date() let date2 = "Jan 1, 2019" console.log('Date 1: ${date1}') console.log('Date 2: ${date2}') let first_date = new Date(date1) let second_date = new Date(date2) // pass each of the date to 'new Date(yourDate)' // and get the similar format dates console.log('first Date: ${first_date}') console.log('second Date: ${second_date}') // now these dates are comparable if(first_date > second_date) { console.log('${date2} has been passed') } 
0
source

Source: https://habr.com/ru/post/1496984/


All Articles