[英]What is the best way to determine if a date is today in JavaScript?
I have a date object in JavaScript and I want to figure out if that date is today.我在 JavaScript 中有一个日期对象,我想确定该日期是否是今天。 What is the fastest way of doing this?
这样做的最快方法是什么?
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
。
You could use toDateString
:您可以使用
toDateString
:
var d = new Date()
var bool = (d.toDateString() === otherDate.toDateString());
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();
}
MDN has a decent overview of the JS Date object API if this isn't quite what you need.如果这不是您所需要的, MDN对 JS 日期对象 API 有一个不错的概述。
var someDate = new Date("6 Dec 2011").toDateString();
var today = new Date().toDateString();
var datesAreSame = (today === someDate);
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?几乎相同的问题: 如何检查输入日期是否等于今天的日期?
我更喜欢使用时刻库
moment('dd/mm/yyyy').isSame(Date.now(), 'day');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.