使用自定义格式验证日期和时间的时刻 [英] moment to validate date and time with custom format
本文介绍了使用自定义格式验证日期和时间的时刻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 moment 来检查所显示的日期/时间是否有效.我有兴趣验证以下格式的日期:
I'm trying to use moment to check if the date/time presented is valid. I'm interested in validating dates in the following format:
10/10/2016 20:45
我已尝试使用此代码,但该日期始终被视为无效:
I've tried using this code, but the date is always considered invalid:
moment("10/10/2016 20:45", "dd/MM/YYYY HH:mm", true);
关于我做错了什么的任何提示?
Any tips on what I'm doing wrong?
谢谢.
路易斯
推荐答案
您在输入字符串中有 2045
,而在格式中有 HH:mm
,问题是:
,将输入改为20:45
或格式为HHmm
.
You have 2045
in the input string, while you have HH:mm
in the format, the problem is the :
, change the input to 20:45
or the format to HHmm
.
此外,day 的标记是大写的 DD
而不是小写的 dd
,请参阅文档 这里.
Moreover the token for day is the uppercase DD
instead of the lowercase dd
, see docs here.
这是一个工作示例:
var m1 = moment("10/10/2016 2045", "dd/MM/YYYY HH:mm", true);
var m2 = moment("10/10/2016 2045", "DD/MM/YYYY HHmm", true);
var m3 = moment("10/10/2016 20:45", "DD/MM/YYYY HH:mm", true);
console.log(m1.isValid()); // false
console.log(m2.isValid()); // true
console.log(m3.isValid()); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
这篇关于使用自定义格式验证日期和时间的时刻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文