【问题标题】:How can I determine whether a given string represents a date?如何确定给定字符串是否代表日期?
【发布时间】:2011-04-22 06:59:04
【问题描述】:

jQuery 中有isDate 函数吗?

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

Date.parse 将把你整理出来,而不需要 jquery:

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

在某个好心人指出 parseDate 的基本原理后,以上内容已被删除。

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

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

【讨论】:

  • var d = Date.parse("13/13/ 2010"); GIVES 1294857000000 :) 所以它不能被使用
  • 哇哦,太糟糕了!我认为它正确地告诉了你日期是否有效。
  • 如果您已经在使用 jQuery UI DatePicker,那么现在可以轻松编写自己的 isDate 函数。
【解决方案2】:

根据您尝试实现此功能的方式,您可以使用 the "validate" jQuery pluginthe date option 设置。

【讨论】:

  • 这不会验证欧洲日期格式 (dd/MM/yyyy)
【解决方案3】:

在 jQuery 核心中没有内置的日期功能......而且它并没有直接帮助处理日期,所以它上面没有很多库(除非它们是日期选择器等)。 There are several JavaScript date libraries available though,让他们的工作更轻松。

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

【讨论】:

    【解决方案4】:

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

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

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

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

    允许月份名称和数字:'21 Jan, 2000' 或 'October 21,1975'

    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;
    }
    

    【讨论】:

      【解决方案5】:

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

      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
      }

      【讨论】:

        【解决方案6】:

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

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

        更新:    !!主要警告!!
        @BarryPicker 在 cmets 中提出了一个很好的观点。对于所有非闰年,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..
        

        【讨论】:

        • 对于 asp.net,如果你使用 CustomValidator 控件,你可以从 ClientValidationFunction 属性调用一个函数,这个函数应该或多或少:function IsDate(sender, args) { var d = new Date($ ('#tbBirthDate').val()); args.IsValid = !isNaN(d.valueOf());返回; }
        • 这个方法在 2014 年 2 月 29 日不能正常工作 - 2014 年没有闰年。事实上,这个方法说 2014 年 2 月 30 日是有效的 - 这永远不会有效。当使用 2/30/2014 作为输入时,变量“d”在函数的第一行被赋值为 2014 年 3 月 2 日,因此发生了一些隐式转换...
        • @barrypicker:感谢您的提醒。我相应地更新了我的答案。
        • 此方法对于不包含字母的十六进制颜色字符串也会失败,例如“#000000”。
        • 请不要回答这个问题,因为它根本不起作用,你会被踢出你的团队。你应该使用 moment js 例如: moment('2012-05-25', 'YYYY-MM-DD', true).isValid();
        【解决方案7】:

        我得到了这个解决方案,因为我使用欧洲格式而变得更加复杂,而 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 = "";
        }
        

        杂乱无章,但能胜任。 如果你的用户是美国人,并且把一天放在中间,(我永远不会明白!),那么你可以省略 newD 的拆分和创建。

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

        【讨论】:

        • 在 ie 中不起作用! (即,将其转换为完全不同的有效日期!)我打算转换我为嵌入式软件编写的 C 函数,该函数根据月份验证日期,但我认为我只需要在日常工作中做这些低级的事情!他们有一个日期选择器,我将使用 VB isdate 验证它的服务器端。工作完成。
        【解决方案8】:

        javascript 中最简单的方法是:

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

        【讨论】:

          【解决方案9】:

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

          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;
              } 
          }
          

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

          【讨论】:

            【解决方案10】:

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

            HTML

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

            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

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

            DEMO

            【讨论】:

              【解决方案11】:

              您应该使用 moment.js,它是处理各种日期的最佳库。 解决您的问题:

              var inputVal = '2012-05-25';
              moment(inputVal , 'YYYY-MM-DD', true).isValid();
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2012-02-29
                • 1970-01-01
                • 1970-01-01
                • 2013-10-16
                • 1970-01-01
                • 2017-12-16
                相关资源
                最近更新 更多