如何使用Moment.js将日期验证为指定格式? [英] How to validate date with Moment.js to a specified format?
问题描述
我无法找到有关如何使用moment.js验证日期输入以确保其格式为 2017-12-31T23:59:59Z的现有问题/答案。
I am unable to find an existing question/answer on how to validate a date input using moment.js to ensure that it is in this format, "2017-12-31T23:59:59Z".
鉴于我已将日期作为字符串, 2017-12-31T23:59:59Z,如何验证日期字符串严格位于指定的格式为 YYYY-MM-DDThh:mm:ssZ。
Given that I've got a date as a string, "2017-12-31T23:59:59Z", how can validate that the date string is strictly in the format specified, "YYYY-MM-DDThh:mm:ssZ".
我尝试了以下操作,但似乎不适用于我。
I've tried the following and it does not seem to work for me.
var dateTime = "2017-12-31T23:59:59Z";
var utc = moment(dateTime, "YYYY-MM-DDThh:mm:ssZ", true)
var isUTC = utc.isValid(dateTime);
console.log(isUTC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
有人可以举几个例子吗?
Could anyone please provide a couple of examples?
预先感谢
-R
Thanks in advance -R
推荐答案
时刻令牌为ca由于敏感,您应该使用大写字母 HH
解析 0-23
小时, hh
用于解析 1-12
。参见 moment(字符串,字符串,布尔值)
文档。
Moment tokens are case sensitive, you should use uppercase HH
to parse 0-23
hours, hh
is for parsing 1-12
. See moment(String, String, Boolean)
docs.
这里有一个在线示例:
var dateTime = "2017-12-31T23:59:59Z";
var utc = moment(dateTime, "YYYY-MM-DDThh:mm:ssZ", true)
var isUTC = utc.isValid();
console.log(isUTC);
utc = moment(dateTime, "YYYY-MM-DDTHH:mm:ssZ", true)
isUTC = utc.isValid();
console.log(isUTC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
这篇关于如何使用Moment.js将日期验证为指定格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!