如何在javascript中比较2种日期格式 [英] How Do I compare 2 date formats in javascript

查看:68
本文介绍了如何在javascript中比较2种日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if(reportDate> = payStartDate && reportDate< = payEndDate)



reportingdate格式为mm / dd / yyyy并且startdate和enddate格式为

Sat Dec 14 00:00:00 EST 2013。因此,我无法比较两个日期。我可以知道如何比较这两种不同的日期格式吗?

解决方案

由于你所有的变量都是Date对象,你可以简单地比较它们。创建Date对象的字符串的原始格式无关紧要...


JavaScript中没有内置日期转换格式,但您可以使用Moment.js (第三方)图书馆。它非常灵活。



http://momentjs.com/ [ ^ ]


您可以使用以下方法解析JavaScript中的日期字符串内置日期对象。



您可以通过一点点Google搜索轻松找到解析JavaScript函数的日期。但是我通过向您提供以下代码来节省您的时间:



  //  返回有意义的日期格式 
function getDate(rawDate){
rawDate = new Date(Date.parse(rawDate));
var month = rawDate.getMonth(),
day = rawDate.getDate(),
year = rawDate.getFullYear() ;
return month + / + day + / + year;
}
console.log(getDate(' Sat Dec 14 00:00:00 EST 2013 ));


if (reportDate >= payStartDate && reportDate <= payEndDate)

reporteddate is in the format of "mm/dd/yyyy" and startdate and enddate are in the format of
Sat Dec 14 00:00:00 EST 2013 . Because of this I couldn't compare both dates. Can I please know how to compare these 2 different date formats?

解决方案

As all your variables are already Date object you can simply compare them. The original format of the string from which the Date object was created does not matter anymore...


There is no in-built date conversion format in JavaScript, but you can use Moment.js (a third-party) library. It's quite flexible.

http://momentjs.com/[^]


You can parse date strings in JavaScript using the inbuilt Date object.

You can easily find date parsing JavaScript functions with a little googling. However I am saving your time by giving you the following code:

//returns meaningful date format
function getDate(rawDate) {
    rawDate = new Date(Date.parse(rawDate));
    var month = rawDate.getMonth(),
        day = rawDate.getDate(),
        year = rawDate.getFullYear();
    return month + "/" + day + "/" + year;
}
console.log(getDate('Sat Dec 14 00:00:00 EST 2013'));


这篇关于如何在javascript中比较2种日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆