如何检查日期字符串是否遵循特定的数据格式

发布于 2025-01-26 06:31:34 字数 448 浏览 1 评论 0原文

我有一个应用程序,用户可以指定自己的数据格式,例如“ MM/DD/YYYY”,“ MM/DD/YY”等

。给定格式。

我尝试使用moment(datastring,dateformat).isvalid(),但看起来它不能

为datestring提供工作:01/01/20

使用DateFormat mm/dd/yyyy,期望false

带有dataformat mm/dd/yy,期望true

> moment('01/01/ 2020 “ mm/dd/yyyy”,true).isvalid() ---期望:true,实际:false

我可以用来实现这一目标的方法?

I have an app, user can specify their own data format, like 'MM/dd/yyyy', 'MM/dd/yy', etc.

Once I receive a date string, I need to validate if the date string is valid for the given format.

I tried to use moment(dataString, dateFormat).isValid(), but looks it does not do the work

For dateString: 01/01/20
with dateFormat MM/dd/yyyy, expect false

with dataFormat MM/dd/yy, expect true

moment('01/01/2020', 'MM/dd/yy').isValid() --- expect: false, actual: true

moment('01/02/2020', 'MM/dd/yyyy', true).isValid() --- expect: true, actual: false

What I can use to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只涨不跌 2025-02-02 06:31:34

您必须将DD大写并在第三个参数中供应真实,以实现严格的解析

console.log(moment('This string includes a date with slashes 01/01/2020', 'MM/DD/YYYY').isValid())
console.log(moment('This string does not include a date with slashes', 'MM/DD/YYYY').isValid())
console.log(moment('01/01/2020', 'MM/DD/YYYY', true).isValid())
console.log(moment('01/01/2020', 'MM/dd/YYYY', true).isValid())
console.log(moment('01/01/20', 'MM/dd/YYYY', true).isValid())
console.log(moment('01/01/20', 'MM/DD/YY', true).isValid())
<script src="https://momentjs.com/downloads/moment.min.js"></script>

you have to capitalize DD and supply true in the 3rd parameter, to enable strict parsing

console.log(moment('This string includes a date with slashes 01/01/2020', 'MM/DD/YYYY').isValid())
console.log(moment('This string does not include a date with slashes', 'MM/DD/YYYY').isValid())
console.log(moment('01/01/2020', 'MM/DD/YYYY', true).isValid())
console.log(moment('01/01/2020', 'MM/dd/YYYY', true).isValid())
console.log(moment('01/01/20', 'MM/dd/YYYY', true).isValid())
console.log(moment('01/01/20', 'MM/DD/YY', true).isValid())
<script src="https://momentjs.com/downloads/moment.min.js"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文