在 JavaScript 中确定日期是否为今天的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8393947/
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
What is the best way to determine if a date is today in JavaScript?
提问by leora
I have a date object in JavaScript and I want to figure out if that date is today. What is the fastest way of doing this?
我在 JavaScript 中有一个日期对象,我想确定该日期是否是今天。这样做的最快方法是什么?
My concern was around comparing date object as one might have a different time than another but any time on today's date should return true
.
我担心的是比较日期对象,因为一个人的时间可能与另一个不同,但今天日期的任何时间都应该返回true
。
回答by Joseph Marikle
You could use toDateString
:
你可以使用toDateString
:
var d = new Date()
var bool = (d.toDateString() === otherDate.toDateString());
回答by recf
The answers based on toDateString()
will work I think, but I personally would avoid them since they basically ask the wrong question.
toDateString()
我认为基于的答案会起作用,但我个人会避免使用它们,因为它们基本上问错了问题。
Here is a simple implementation:
这是一个简单的实现:
function areSameDate(d1, d2) {
return d1.getFullYear() == d2.getFullYear()
&& d1.getMonth() == d2.getMonth()
&& d1.getDate() == d2.getDate();
}
MDNhas a decent overview of the JS Date object API if this isn't quite what you need.
如果这不是您所需要的,MDN对 JS 日期对象 API 有一个不错的概述。
回答by Chris Fulstow
var someDate = new Date("6 Dec 2011").toDateString();
var today = new Date().toDateString();
var datesAreSame = (today === someDate);
回答by AvatarKava
If both are Date() objects, you can use this to 'format' the date in a way that it will only compare on the year/month/day: if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0));
如果两者都是 Date() 对象,您可以使用它来“格式化”日期,使其仅在年/月/日上进行比较: if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0));
Nearly identical question: How to check if input date is equal to today's date?
几乎相同的问题: 如何检查输入日期是否等于今天的日期?
回答by Aleksandr Golovatyi
I prefer to use moment lib
我更喜欢使用时刻库
moment('dd/mm/yyyy').isSame(Date.now(), 'day');