检查日期是否有效 [英] Check if date is a valid one

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

问题描述

以下是该场景:

我有一个 String 日期和不同的日期格式。例如:

日期:2016-10-19

dateFormat:DD-MM-YYYY。

I have a String date and a date format which is different. Ex.:
date: 2016-10-19
dateFormat: "DD-MM-YYYY".

I需要检查这个日期是否有效。

I need to check if this date is a valid date.

我试过以下事情

var d = moment("2016-10-19",dateFormat);

d.isValid()正在返回<每次code> false 。 Moment.js是否以给定格式解析日期?

d.isValid() is returning false every time. Does not Moment.js parse the date in the given format?

然后我尝试在 DD-MM-YYYY 首先将其传递给Moment.js:

Then I tried to format the date in DD-MM-YYYY first and then pass it to Moment.js:

var d = moment("2016-10-19").format(dateFormat);
var date = moment(d, dateFormat);

现在 date.isValid()正在给予我想要的结果,但这里Moment.js日期对象创建了两次。我怎么能避免这个?有没有更好的解决方案?

Now date.isValid() is giving me the desired result, but here the Moment.js date object is created twice. How can I avoid this? Is there a better solution?

仅供参考我不能更改 dateFormat

推荐答案

能够找到解决方案。
由于我得到的日期是ISO格式,只提供日期到时间验证它,不需要传递dateFormat。

Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

然后 date.isValid()给出期望的结果。

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

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