Javascript 如何判断两个日期是否在同一天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43855166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to tell if two dates are in the same day?
提问by reza
I am using the moment npm module. I am comparing two dates and want to see if there in the same day.
我正在使用时刻 npm 模块。我正在比较两个日期,想看看是否在同一天。
Is there a clean way of doing that using the moment package or using straight javascript or typescript?
使用 moment 包或使用直接的 javascript 或 typescript 有没有一种干净的方法来做到这一点?
回答by Pointy
The Date prototype has APIs that allow you to check the year, month, and day-of-month, which seems simple and effective.
Date 原型具有允许您检查年、月和月日的 API,这看起来简单而有效。
You'll want to decide whether your application needs the dates to be the same from the point of view of the locale where your code runs, or if the comparison should be based on UTC values.
您需要从代码运行的区域设置的角度来决定您的应用程序是否需要相同的日期,或者是否应该基于 UTC 值进行比较。
function sameDay(d1, d2) {
return d1.getFullYear() === d2.getFullYear() &&
d1.getMonth() === d2.getMonth() &&
d1.getDate() === d2.getDate();
}
There are corresponding UTC getters getUTCFullYear(), getUTCMonth(), and getUTCDate().
有相应的UTC干将getUTCFullYear(),getUTCMonth()和getUTCDate()。
回答by Daniel Taub
var isSameDay = (dateToCheck.getDate() === actualDate.getDate()
&& dateToCheck.getMonth() === actualDate.getMonth()
&& dateToCheck.getFullYear() === actualDate.getFullYear())
That will ensure the dates are in the same day.
这将确保日期在同一天。
Read more about Javascript
Dateto string
阅读有关 Javascript到字符串的更多信息
Date

