gpt4 book ai didi

javascript - Moment.js : Check if string is in correct format

转载 作者:行者123 更新时间:2023-12-01 07:34:23 25 4
gpt4 key购买 nike

我正在使用具有特定格式字符串的正则表达式检查时刻字符串是否正确:

const isCorrect = isCorrectFormat('12/06/2016 20:20:20:444')

isCorrectFormat 功能:
const isCorrectFormat = (dateString) => {
const regex = /[0-3][0-9][/][0-9]{2}[/][0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]*/
return regex.test(dateString)
}

当然,这种情况下的结果将是 因为没有使用相同的格式。

我现在要解决的问题是将格式也作为参数发送,但我想直接使用 moment 而不是使用正则表达式格式规范。
const isCorrect = isCorrectFormat(
'12/06/2016 20:20:20:444',
'MM/DD/YYYY HH:mm:ss.SSS'
)

但我不知道如何实现它......我在 moment 的文档中找到了,我没有看到任何测试它的方法。任何的想法?

非常感谢!!

最佳答案

您可以使用时刻 strict parsing isValid 方法。

moment(String, String) 中所述文档:

Moment's parser is very forgiving, and this can lead to undesired/unexpected behavior.

As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.



Herea工作示例:

const isCorrectFormat = (dateString, format) => {
return moment(dateString, format, true).isValid()
}

const isCorrect = isCorrectFormat(
'12/06/2016 20:20:20:444',
'MM/DD/YYYY HH:mm:ss.SSS'
)

console.log(isCorrect);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

关于javascript - Moment.js : Check if string is in correct format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45325324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com