使用JavaScript查看日期 [英] Check date in JavaScript

查看:82
本文介绍了使用JavaScript查看日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过用户输入获取三个变量,其中包含日期,月份和日期的年份。我已经检查了月份var是否在1-12之间,所以。

I get three variables through a user input, that contain the year of a date, the month and the day. I've already checked if the month var is between 1–12 and so on.

现在我想检查一下它是否是真实的日期,而不是日期,

Now I want to check if it's a real date and not a date that doesn't exist like 31–06–2011.

我的第一个想法是创建一个新的Date实例:

My first idea was to make a new Date instance:

var year = 2011;
var month = 5; // five because the months start with 0 in JavaScript - June
var day = 31;
var myDate = new Date(2011,5,31);
console.log(myDate);

但是,MyDate不返回false,因为它不是有效的日期。相反,它返回'Fri Jul 01 2011 [...]'。

But myDate doesn't return false, because it's not a valid date. Instead it returns 'Fri Jul 01 2011 [...]'.

任何想法如何检查无效的日期?

Any ideas how I can check for an invalid date?

推荐答案

尝试这样:

if ((myDate.getMonth()+1!=month)||(myDate.getDate()!=day)||(myDate.getFullYear()!=year))
    alert("Date Invalid.");

这篇关于使用JavaScript查看日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆