检查日期是否有效

检查日期是否有效

问题描述:

以下是该场景:

我有一个 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()正在返回 false 。 Moment.js是否以给定格式解析日期?

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

然后我尝试在 DD-MM-YYYY $中格式化日期c $ c>首先将其传递给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()给出期望的结果。