简体   繁体   中英

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?

如果不使用第三方库,您可以使用这两种格式创建新的Date对象,使用getTime()检索毫秒数(自1970年1月1日午夜起getTime() ,然后只需使用>

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

I strongly recommend using datejs library .

Thus this can be written in one single line:

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

I would make sure that I am comparing the "date" element of each format and exclude any "time" element. Then with both dates converted to milliseconds, simply compare the values. You could do something like this. If dates are equal it returns 0, if the first date is less that the second then return -1, otherwise return 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));

On jsfiddle

也许您可以使用Date.parse("2013/08/26")并与之前的版本进行比较

Follow these steps to compare dates

Each of your date must to passed through Date object ie new Date(yourDate) . Now dates will have same format and these 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`) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM