gpt4 book ai didi

javascript - 使用 Javascript 检查日期是否为给定格式

转载 作者:行者123 更新时间:2023-11-30 07:01:04 25 4
gpt4 key购买 nike

如何检查日期是否为给定格式。一定是这样的功能

function isInGivenFormat(date,format)
{
//some checking
}

例如,isInGivenFormat("12:45:02","hh:mm:ss") 必须返回 true 而 isInGivenFormat("12:45:02 PM","hh:mm:ss") 必须返回 false。
如何使用 Javascript/Jquery 实现此功能?

最佳答案

我建议您查看 Date.js 库。它处理这种情况(以及更多)。

特别是 parseExact()方法解决了这个问题。

Date.parseExact ( String dateString, String formatStringOrArray ) : Date

使用指定的格式(字符串)或格式(数组)将指定的字符串值转换为其等效的 JavaScript 日期。字符串值的格式必须与提供的格式之一完全匹配。

例子

Date.parseExact("12:45:02 PM","hh:mm:ss"); // returns null
Date.parseExact("10/15/2004", "M/d/yyyy"); // The Date of 15-Oct-2

关于javascript - 使用 Javascript 检查日期是否为给定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9738290/

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