如何仅比较日期部分而不比较 JavaScript 中的时间?
要在 javascript 中获取日期和时间,我们有Date()类。我们通过创建对象来访问Date()类。 Date()类返回日期和时间的组合。
实例化日期有四种方法:
句法:
var d = new Date();
//returns the present date and time
或者
var d = new Date(milliseconds);
//to set a specific date
或者
var d = new Date(dateString);
//to set a specific date
或者
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
//to set a specific date:
所以 Date() 返回函数Date() { [native code] }我们可以使用object.toString()将其转换为字符串
方法一:
当对象进行比较时,它会与时间和日期进行比较。
所以现在我们将以这种方式将时间设置为 00:00:00(停止),当比较对象时只比较日期,因为两个日期对象的时间都是 00:00:00(停止)。
要将时间设置为 00:00:00(停止), setHours()就派上用场了。
句法;
//the hour(0-23) is mandatory.
dateobject.setHours(hour, min, sec, millisec)
为了使时间为 0 或完全停止,我们必须确保所有参数都为 0,包括毫秒。
例子:
Below date1 and data2 are compared for older, further, and same dates.
输出
Below date1 and data2 are compared for older, further, and same dates.
date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time)
date2=>Sun Sep 20 2020 00:00:00 GMT+0530 (India Standard Time)
date1 is older than date2
date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time)
date2=>Tue Dec 03 2019 00:00:00 GMT+0530 (India Standard Time)
date1 is further than date2
date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time)
date2=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time)
date1 and date2 same.
date1=>Wed Dec 04 2019 00:00:00 GMT+0530 (India Standard Time)
date2=>Wed Dec 04 2019 05:37:26 GMT+0530 (India Standard Time)
date1 is older than date2
方法二:
这里我们将使用toDateString()来获取唯一的日期,但是当获取它时会被转换为字符串,因为字符串无法进行比较,我们需要再次转换为日期对象,现在将它们转换回对象时间设置为00:00:00(stops) 。
句法:
var date1 = new Date(new Date().toDateString());
上述语法的分解
new Date().toDateString()
converts the Date object to a string containing only the date part.
new Date(new Date().toDateString());
converts it back to Date object setting time to 00:00:00
例子
Below date1 and data2 are compared for older,
further, and same dates.
输出
Below date1 and data2 are compared for older, further, and same dates.
date1=>Fri Dec 20 2019 00:00:00 GMT+0530 (India Standard Time)
date2=>Thu Sep 20 2018 00:00:00 GMT+0530 (India Standard Time)
date1 is further than date2