Javascript 如何测试字符串是否有效日期或不使用时刻?

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

How to test a string is valid date or not using moment?

javascriptjqueryvalidationdatemomentjs

提问by Valamas

I would like to test if a date and or time entered is valid.

我想测试输入的日期和/或时间是否有效。

Can this be done with moment as date and time testing with javascript seems a nightmare. (have spent hours on this).

这可以通过瞬间完成,因为使用 javascript 进行日期和时间测试似乎是一场噩梦。(在这上面花了几个小时)。

Test data looks like this.

测试数据看起来像这样。

Invalid

无效的

invalid = ""
invalid = " "
invalid = "x"
invalid = "1/1"
invalid = "30/2/2015"
invalid = "2/30/2015"

Is Valid

已验证

isvalid = "1/12/2015"
isvalid = "1/12/2015 1:00 PM";

Have tried various javascript methods with hours of trials failing.

尝试了各种 javascript 方法,但经过数小时的试验都失败了。

I thought moment would have something for this. So tried the following, all of which does not work because I do no think moment works like this.

我认为时刻会为此有所作为。所以尝试了以下,所有这些都不起作用,因为我不认为时刻是这样的。

var valid = moment(input).isDate()
var valid = moment().isDate(input)

My time format is "dd/mm/yyyy"

我的时间格式是“dd/mm/yyyy”

采纳答案by Kokizzu

Yes, you could use momentjs to parse it and compare it back with the string

是的,您可以使用 momentjs 来解析它并将其与字符串进行比较

function isValidDate(str) {
  var d = moment(str,'D/M/YYYY');
  if(d == null || !d.isValid()) return false;

  return str.indexOf(d.format('D/M/YYYY')) >= 0 
      || str.indexOf(d.format('DD/MM/YYYY')) >= 0
      || str.indexOf(d.format('D/M/YY')) >= 0 
      || str.indexOf(d.format('DD/MM/YY')) >= 0;
}

Test code

测试代码

tests = ['',' ','x','1/1','1/12/2015','1/12/2015 1:00 PM']
for(var z in tests) {
  var test = tests[z];
  console.log('"' + test + '" ' + isValidDate(test));
}

Output

输出

 "" false
 " " false
 "x" false
 "1/1" false
 "1/12/2015" true
 "1/12/2015 1:00 PM" true

回答by Luca Fagioli

Moment has a function called isValid.

Moment 有一个名为 的函数isValid

You want to use this function along with the target date formatand the strict parsing parameter to true(otherwise your validation might not be consistent) to delegate to the library all the needed checks (like leap years):

您希望将此函数与目标日期格式严格解析参数一起使用为 true(否则您的验证可能不一致),以将所有需要的检查(如闰年)委托给库:

var dateFormat = "DD/MM/YYYY";
moment("28/02/2011", dateFormat, true).isValid(); // return true
moment("29/02/2011", dateFormat, true).isValid(); // return false: February 29th of 2011 does not exist, because 2011 is not a leap year

回答by user48447

You can use the Date.parse() function.

您可以使用 Date.parse() 函数。

Hereis the details of how to use.

下面是具体的使用方法。