检查用户输入的日期是当前日期还是将来日期
问题描述:
我正在网上浏览找到一个javascript函数
,它可以检查用户输入的日期是当前日期还是未来日期,但我没有找到合适的答案,所以我自己做了。想知道如果这可以通过一行代码实现。
I was browsing through the net to find a javascript function which can check whether the date entered by the user is current date or the future date but i didn't found a suitable answer so i made it myself.Wondering If this can be achieved by one line code.
function isfutureDate(value)
{
var now = new Date;
var target = new Date(value);
if (target.getFullYear() > now.getFullYear())
{
return true;
}
else if(target.getFullYear() == now.getFullYear())
{
if (target.getMonth() > now.getMonth()) {
return true;
}
else if(target.getMonth() == now.getMonth())
{
if (target.getDate() >= now.getDate()) {
return true;
}
else
{
return false
}
}
}
else{
return false;
}
}
答
你可以将两个日期比较为整数:
You can compare two dates as if they were Integers:
var now = new Date();
if (before < now) {
// selected date is in the past
}
两者都必须是日期。
谷歌首次搜索会导致:检查日期是否是过去的Javascript
First search in google leads to this: Check if date is in the past Javascript
但是,如果你喜欢编程,这里有一个提示:
However, if you love programming, here's a tip:
- 格式化为YYYY-MM-DD的日期可能是28-12- 2013年。
- 如果我们撤销日期,则为2013-12-28。
- 我们删除冒号,我们得到20131228。 / li>
- 我们设定另一个日期:2013-11-27,最后是20131127。
- 我们可以执行一个简单的操作:20131228 - 20131127
- A date formatted like YYYY-MM-DD could be something like 28-12-2013.
- And if we reverse the date, it is 2013-12-28.
- We remove the colons, and we get 20131228.
- We set an other date: 2013-11-27 which finally is 20131127.
- We can perform a simple operation: 20131228 - 20131127
享受。