繁体   English   中英

javascript - 比较不同格式的日期

[英]javascript - compare dates in different formats

我有两个日期,我需要比较,看看是否有一个比另一个更大,但他们有不同的格式,我不知道比较2的最佳方式。

格式是:

1381308375118 (这是var futureDate)

由...创建

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

而另一种格式是

2013/08/26

我有什么想法可以比较2吗?

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

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

我强烈建议使用datejs库

因此,这可以写在一行:

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

我会确保我正在比较每种格式的“日期”元素并排除任何“时间”元素。 然后将两个日期转换为毫秒,只需比较这些值。 你可以这样做。 如果日期相等则返回0,如果第一个日期小于第二个日期则返回-1,否则返回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

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

请按照以下步骤比较日期

您的每个日期必须通过Date对象,即new Date(yourDate) 现在日期将具有相同的格式,这些将具有可比性

 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`) } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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