Javascript 如何确定给定的字符串是否代表日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3880615/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:29:05  来源:igfitidea点击:

How can I determine whether a given string represents a date?

javascriptjquery

提问by Kuttan Sujith

Is there an isDatefunction in jQuery?

isDatejQuery 中有函数吗?

It should return trueif the input is a date, and falseotherwise.

true如果输入是日期,它应该返回,false否则返回。

采纳答案by irishbuzz

Depending on how you're trying to implement this, you may be able to use the "validate" jQuery pluginwith the dateoptionset.

这取决于你如何努力实现这一点,您可以使用“验证” jQuery插件使用date选项设置。

回答by mwolfe02

If you don't want to deal with external libraries, a simple javascript-only solution is:

如果您不想处理外部库,一个简单的 javascript-only 解决方案是:

function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}


UPDATE:     !!Major Caveat!!
@BarryPicker raises a good point in the comments. JavaScript silently converts February 29 to March 1 for all non-leap years. This behavior appears to be limited strictly to days through 31 (e.g., March 32 is not converted to April 1, but June 31 is converted to July 1). Depending on your situation, this may be a limitation you can accept, but you should be aware of it:

更新:!!主要警告!!
@BarryPicker 在评论中提出了一个很好的观点。JavaScript 默默地将所有非闰年的 2 月 29 日转换为 3 月 1 日。此行为似乎严格限制到 31 天(例如,3 月 32 日不会转换为 4 月 1 日,但 6 月 31 日会转换为 7 月 1 日)。根据您的情况,这可能是您可以接受的限制,但您应该意识到这一点:

>>> new Date('2/29/2014')
Sat Mar 01 2014 00:00:00 GMT-0500 (Eastern Standard Time)
>>> new Date('3/32/2014')
Invalid Date
>>> new Date('2/29/2015')
Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)
>>> isDate('2/29/2014')
true  // <-- no it's not true! 2/29/2014 is not a valid date!
>>> isDate('6/31/2015')
true  // <-- not true again! Apparently, the crux of the problem is that it
      //     allows the day count to reach "31" regardless of the month..

回答by Nick Craver

There's no built-in date functionality in jQuery core...and it doesn't really do anything directly to help with dates, so there aren't many libraries on top of it (unless they're date pickers, etc). There are several JavaScript date libraries available though, to make working with them just a bit easier.

jQuery 核心中没有内置日期功能......而且它并没有直接做任何事情来帮助处理日期,所以它上面没有很多库(除非它们是日期选择器等)。 不过有几个 JavaScript 日期库可用,使使用它们更容易一些。

I can't answer for sure what's best...it depends how they're entering it and what culture you're dealing with, keep in mind that different cultures are used to seeing their dates in different format, as a quick example, MM/DD/YYYYvs YYYY/MM/DD(or dozens of others).

我无法确定什么是最好的......这取决于他们如何进入它以及您正在处理的文化,请记住,不同的文化习惯于以不同的格式查看他们的日期,作为一个简单的例子,MM/DD/YYYYvs YYYY/MM/DD(或其他几十个)。

回答by isambitd

simplest way in javascript is:

javascript中最简单的方法是:

function isDate(dateVal) {
  var d = new Date(dateVal);
  return d.toString() === 'Invalid Date'? false: true;
}

回答by invot

The problem is that entering in February 31st will return a valid date in JavaScript. Enter in the year, month, and day, turn it into a date, and see if that date matches what you input, instead of some day in March.

问题是在 JavaScript 中输入 2 月 31 日将返回一个有效日期。输入年、月和日,将其转换为日期,然后查看该日期是否与您输入的日期相匹配,而不是三月的某一天。

function isDate(y, m, d) {
    var a = new Date(y, m-1, d); 
    // subtract 1 from the month since .getMonth() is zero-indexed.
    if (a.getFullYear() == y && a.getMonth() == m-1 && a.getDate() == d) { 
        return true; 
    } else {
        return false;
    } 
}

Technically, this is vanilla JavaScript, since jQuery doesn't really expand on the native Date object.

从技术上讲,这是普通的 JavaScript,因为 jQuery 并没有真正扩展原生 Date 对象。

回答by kennebec

The best way to get user date input is a date picker that only provides valid dates. It can be done with a string, but you are liable to rile your users by demanding they use your chosen format.

获取用户日期输入的最佳方式是只提供有效日期的日期选择器。可以使用字符串来完成,但您可能会要求他们使用您选择的格式,从而激怒您的用户。

You need to specify in your validator if dates precede months.

如果日期早于几个月,您需要在验证器中指定。

This uses a second argument to enforce the order. With no second argument it uses the computer's default order.

这使用第二个参数来强制执行命令。没有第二个参数,它使用计算机的默认顺序。

// computer default date format order:
Date.ddmm= (function(){
    return Date.parse('2/6/2009')> Date.parse('6/2/2009');
})()

allow month names as well as digits: '21 Jan, 2000' or 'October 21,1975'

允许月份名称和数字:“2000 年 1 月 21 日”或“1975 年 10 月 21 日”

function validay(str, order){
    if(order== undefined) order= Date.ddmm? 0: 1;
    var day, month, D= Date.parse(str);
    if(D){
        str= str.split(/\W+/);

        // check for a month name first:
        if(/\D/.test(str[0])) day= str[1];
        else if (/\D/.test(str[1])) day= str[0];
        else{
            day= str[order];
            month= order? 0: 1;
            month= parseInt(str[month], 10) || 13;
        }
        try{
            D= new Date(D);
            if(D.getDate()== parseInt(day, 10)){
                if(!month || D.getMonth()== month-1) return D;
            }
        }
        catch(er){}
    }
    return false;
}

回答by Matt Roberts

Date.parse will prb sort you out, without the need for jquery:

Date.parse 将 prb 整理你,而不需要 jquery:

http://www.w3schools.com/jsref/jsref_parse.asp

http://www.w3schools.com/jsref/jsref_parse.asp

Above removed after some kind soul pointed out how basic parseDate really is.

在某些善良的灵魂指出基本的 parseDate 真的是之后,上面删除了。

There is also a $.datepicker.parseDate( format, value, options )utility function in the JQuery UI Datepicker plugin:

$.datepicker.parseDate( format, value, options )JQuery UI Datepicker 插件中还有一个实用函数:

https://api.jqueryui.com/datepicker/

https://api.jqueryui.com/datepicker/

回答by user2981217

I arrived at this solution, made more complicated as I use the European format and javascript is clearly american!

我找到了这个解决方案,因为我使用欧洲格式而变得更加复杂,而 javascript 显然是美国的!

function CheckDate()
{
    var D = document.getElementById('FlightDate').value;
    var values = D.split("-")
    var newD = values [1] + "/" + values [0] + "/" + values[2]
    var d = new Date(newD);
    if(d == 'Invalid Date')document.getElementById('FlightDate').value = "";
}

Messy, but does the job. If your users are american and put the day in the middle, (which I'll never understand!), then you can leave out the split and creation of the newD.

凌乱,但可以完成工作。如果您的用户是美国人并且将一天放在中间(我永远不会明白!),那么您可以省略 newD 的拆分和创建。

It is probable that I can override the default americanism in the JS by setting culture or some such, but my target audience is exclusively European so it was easier to rig it this way. (Oh, this worked in Chrome, haven't tested it on anything else.)

我可能可以通过设置文化或类似的东西来覆盖 JS 中的默认美国主义,但我的目标受众完全是欧洲人,因此以这种方式操纵它更容易。(哦,这在 Chrome 中有效,还没有在其他任何东西上测试过。)

回答by Mike Cheel

If you don't want to use the jquery plugin I found the function at:

如果您不想使用 jquery 插件,我在以下位置找到了该功能:

http://www.codetoad.com/forum/17_10053.asp

http://www.codetoad.com/forum/17_10053.asp

Works for me. The others I found don't work so well.

为我工作。我发现的其他人效果不佳。

UPDATED:

更新:

From the cached version of the page at: http://web.archive.org/web/20120228171226/http://www.codetoad.com/forum/17_10053.asp

来自页面的缓存版本:http: //web.archive.org/web/20120228171226/http: //www.codetoad.com/forum/17_10053.asp

// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************

function isDate(dateStr) {

    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
        return false;
    }

    month = matchArray[1]; // p@rse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
        alert("Month " + month + " doesn`t have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day == 29 && !isleap)) {
            alert("February " + year + " doesn`t have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}

回答by Vikash Mishra

I guess you want something like this. +1 if it works for you.

我猜你想要这样的东西。+1 如果它适合你。

HTML

HTML

 Date : <input type="text" id="txtDate" /> (mm/dd/yyyy)
 <br/><br/><br/>
<input type="button" value="ValidateDate" id="btnSubmit"/>

jQuery

jQuery

$(function() {
$('#btnSubmit').bind('click', function(){
    var txtVal =  $('#txtDate').val();
    if(isDate(txtVal))
        alert('Valid Date');
    else
        alert('Invalid Date');
});

function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
    return false;

var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?

if (dtArray == null) 
    return false;

//Checks for mm/dd/yyyy format.
dtMonth = dtArray[1];
dtDay= dtArray[3];
dtYear = dtArray[5];        

if (dtMonth < 1 || dtMonth > 12) 
    return false;
else if (dtDay < 1 || dtDay> 31) 
    return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
    return false;
else if (dtMonth == 2) 
{
    var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
    if (dtDay> 29 || (dtDay ==29 && !isleap)) 
            return false;
}
return true;
}

});

CSS

CSS

body{
font-family:Tahoma;
font-size : 8pt;
padding-left:10px;
}
input[type="text"]
{
font-family:Tahoma;
font-size : 8pt;
width:150px;
}

DEMO

演示