简体   繁体   English

如何验证其中包含时区的日期字符串的格式?

[英]How can I validate the formate of a date string that has timezone in it?

If I have a this date: April 14, 2022 14:00 UTC , how I can validate that it is in MMMM DD, YYYY HH:mm <timezone> ?如果我有这个日期: April 14, 2022 14:00 UTC ,我如何验证它是在MMMM DD, YYYY HH:mm <timezone>中?

I tried it with moment but it doesn't have format for timezone.我用moment试了一下,但它没有时区格式。

moment(date, 'MMMM DD, YYYY HH:mm',true).isValid()

How can I validate that the string is in MMMM DD, YYYY HH:mm <timezone> format?如何验证字符串是否为MMMM DD, YYYY HH:mm <timezone>格式?

You can include " UTC" as literal text in the parse format, eg您可以在解析格式中包含“UTC”作为文字文本,例如

 let date = 'April 14, 2022 14:00 UTC'; console.log( moment(date, 'MMMM DD, YYYY HH:mm[ UTC]',true).isValid() );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

Per the moment.js documentation , various offset formats are supported, so if there are other offset representations you can use multiple tests to support say "UTC" and "+00:00" (or ±HH:mm in general), eg根据moment.js 文档,支持各种偏移格式,因此如果有其他偏移表示,您可以使用多个测试来支持说“UTC”和“+00:00”(或一般的 ±HH:mm),例如

 ['April 14, 2022 14:00 UTC', 'April 14, 2022 14:00 +00:00', 'April 14, 2022 14:00 +05:30' ].forEach(date => console.log(`${date} is valid? ` + `${moment(date, 'MMMM DD, YYYY HH:mm[ UTC]', true).isValid() || moment(date, 'MMMM DD, YYYY HH:mm Z', true).isValid()}` ) );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

Unfortunately isValid doesn't support multiple formats in the one call so you can't do:不幸的是isValid在一个调用中不支持多种格式,所以你不能这样做:

moment(date, 'MMMM DD, YYYY HH:mm[ UTC]',  'MMMM DD, YYYY HH:mm Z', true).isValid()

as only the first format is recognised.因为只识别第一种格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM