简体   繁体   English

如何比较JavaScript中的2个变量以查看日期是否相同?

[英]How can I compare the 2 variables in JavaScript to see if the dates are the same?

I have 2 variables. 我有2个变量。 How can I compare the 2 variables in JavaScript to see if the dates are the same? 如何比较JavaScript中的2个变量以查看日期是否相同? I don't want to conevert the 2 dates with time. 我不想随时间推移两个日期。 i just want to convert them into yyyy/dd/mm format. 我只想将它们转换为yyyy / dd / mm格式。

var DateReported = "20/04/2011";
var StartDate = "16/04/2011";

I have to do something if StartDate < DateReported and something else if StartDate > DateReported 如果StartDate <DateReported,我必须做一些事情;如果StartDate> DateReported,我必须做其他事情。

Thanks 谢谢

If you have your dates stored as strings in the same date format, there's no reason why you can't you string comparison to check if they're equal: 如果您以相同的日期格式将日期存储为字符串,则没有理由不进行字符串比较以检查它们是否相等:

var DateReported = "20/04/2011";
var StartDate = "16/04/2011";

return DateReported == StartDate;  // returns false;

Update : if you actually need to compare the dates to determine which is the most recent, I'd recommend making use of a library - eg the jQuery UI module contains date handling code, so you can easily parse date strings: 更新 :如果您实际上需要比较日期以确定哪个是最新的,我建议您使用一个库-例如jQuery UI模块包含日期处理代码,因此您可以轻松地解析日期字符串:

var dReported = $.datepicker.formatDate('d/mm/yy', DateReported);
var dStarted = $.datepicker.formatDate('d/mm/yy', StartDate);

if (dReported > dStarted) { ... }

by == operator 由==运算符

if(DateReported == StartDate)
return true;

else create the date object and convert them to millisecond and then compare for > / < 否则创建日期对象并将其转换为毫秒,然后比较> / <

DateReported = new Date(2011,4,20);
StartDate= new Date(2011,4,16);

if (DateReported .getTime()<StartDate.getTime()) {
  alert('DateReported is less than StartDate');
}

If you don't want to use conversion to date, try this(I assume the months and days are always 0 padded): 如果您不想使用转换日期,请尝试以下操作(我假设月和日始终填充为0):

var DateReported = "20/04/2011"; 
var StartDate = "16/04/2011";
var regExp = /(\d{2})\/(\d{2})\/(\d{4})/;
if
(
    StartDate.replace(regExp, "$3$2$1") < DateReported.replace(regExp, "$3$2$1")
)
{
    alert("Lesser");
}
else
{
    alert("Greater");
}

Working Example: http://jsfiddle.net/GE83j/ 工作示例: http : //jsfiddle.net/GE83j/

Try this: 尝试这个:

var DateReported = "20/04/2011";
var StartDate = "16/04/2011";
DateReported = new Date(DateReported).format("yyyy/dd/MM");
StartDate = new Date(StartDate).format("yyyy/dd/MM");
if (DateReported > StartDate) {
     alert("Date Reported Greater");
}
else {
     alert("Start Date Greater");
}

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

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