简体   繁体   English

用JavaScript比较不同格式的日期

[英]Comparing Dates with different formats in Javascript

I'm attempting to compare 2 dates that have 2 different formats in Javascript. 我正在尝试比较2个在Javascript中具有2种不同格式的日期。

The date from my database is 2013-04-21 (date1) and the date in the array prints out in the following format in my Chrome debugger: Sun Apr 21 2013 15:37:05 GMT-0400 (Eastern Daylight Time) (date2) 我数据库中的日期是2013-04-21 (date1),数组中的日期在我的Chrome调试器中以以下格式打印: Sun Apr 21 2013 15:37:05 GMT-0400 (Eastern Daylight Time) (date2 )

I'd like to compare only the date part and leave out the time: date1 == date2 is true. 我只想比较日期部分,而忽略时间: date1 == date2是true。

How would I go about formatting the dates so I'd be able to compare them? 我该如何格式化日期,以便能够比较它们?

Any help is greatly appreciated. 任何帮助是极大的赞赏。

y = date2.getFullYear();
m = date2.getMonth()+1;
m = (m<10)? ('0'+m) : m;
d = date2.getDate();
d2 = y+'-'+m+'-'+d;

if (date1 == d2) {
  // do something
}
date1.toISOString().split("T")[0] == date2.toISOString().split("T")[0]

We have to go a little deeper here: we have to distinguishe between Strings storing date, and the Date object which can store dates and do computation with dates. 我们在这里必须更深入一点:我们必须区分存储日期的字符串和可以存储日期并使用日期进行计算的Date对象。

From your description i guess that date1 is acutally a string "2013-04-21" while date2 is already a Date object. 根据您的描述,我猜想date1实际上是字符串“ 2013-04-21”,而date2已经是Date对象。

You could convert date1 to a date object: 您可以将date1转换为日期对象:

date1AsObject = new Date("2013-04-21");

Then you could compute the difference between them: 然后,您可以计算它们之间的差异:

diff = date2 - date1AsObject

the result will be in milliseconds. 结果将以毫秒为单位。

or you could convert date2 to a string like Crayon Violent suggested: 或者您可以将date2转换为Crayon Violent建议的字符串:

y = date2.getFullYear();
m = date2.getMonth()+1;
d = date2.getDate();
date2AsString = y+'-'+m+'-'+d;

then you can compare the two strings. 然后您可以比较两个字符串。

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

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