如何转换这两种日期时间格式进行比较?

一种是形式:

2020-09-20T16:26:38.000Z

另一种形式是:

Sun Sep 20 2020 00:00:00 GMT-0400 (Eastern Daylight Time)

我只想比较日、月、年。因此,这两个日期应该相等。如何在 javascript 中转换两个日期以使它们相等?


qq_遁去的一_1
浏览 93回答 3
3回答

森林海

以下代码片段假定日期是字符串。对于其中任何一个是Date对象的,var dx=new Date(String)都可以跳过。var str1="2020-09-20T16:26:38.000Z";var str2="Sun Sep 20 2020 00:00:00 GMT-0400 (Eastern Daylight Time)";var d1=new Date(str1);var d2=new Date(str2);console.log("str1="+str1);console.log("str2="+str2);console.log("d1="+d1);console.log("d2="+d2);console.log("d1.toDateString()==d2.toDateString() is "+(d1.toDateString()==d2.toDateString()));.as-console-wrapper { max-height: 100% !important; top: 0; }

富国沪深

刚刚新的日期使用Date.getMonth()或Date.getFullYear()const a=new Date("Sun Sep 20 2020 00:00:00 GMT-0400 (Eastern Daylight Time)")console.log(a)//2020-09-20T04:00:00.000Z//result aconst b=new Date("2020-09-20T16:26:38.000Z")console.log(b)//2020-09-20T16:26:38.000Z// result bif (a.getMonth()===b.getMonth())console.log("match")else console.log("not match")

阿晨1998

您可以将它们都转换为 Date 对象(以便获得相同的格式),然后将它们转换回字符串。由于前 15 个字符现在都是日期,因此您可以对它们进行子字符串化并进行比较。编辑:你不必真正转换第二个,因为它已经是正确的格式,但为了彻底起见,我做了let d1 = new Date('2020-09-20T16:26:38.000Z').toString().substring(0, 15),    d2 = new Date('Sun Sep 20 2020 00:00:00 GMT-0400').toString().substring(0, 15);console.log(d1 === d2); //true
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript