gpt4 book ai didi

javascript - 检查momentjs中日期文本是否有毫秒和秒

转载 作者:行者123 更新时间:2023-12-01 01:47:04 24 4
gpt4 key购买 nike

我正在尝试从文本格式解析日期,以查看其中是否包含毫秒和秒。例如

let text = '2016-02-02 14:30:34.234';
const timezone = 'America/Los_Angeles';
// const hasMS = utcParse('%Y-%m-%d %H:%M:%S.')(text);
// const hasSeconds = utcParse('%Y-%m-%d %H:%M:')(text);

const hasMS = !!moment.tz(text, 'YYYY-MM-DD HH:MM:ss.', timezone);
console.log('hasMS', hasMS);
const hasSeconds = !!moment.tz(text, 'YYYY-MM-DD HH:MM:', timezone);
console.log('hasSeconds', hasSeconds);

基本上我正在尝试替换注释的代码。 d3.time-format 中的 utcParse() 将检查日期文本中是否包含毫秒和秒。我为 momentjs 库尝试了一些方法,但似乎不起作用。

最佳答案

通过使用正则表达式,您可以检查字符串的某些部分是否存在。

如果您使用字符串调用 matchDateTime(),您将获得一个包含所有匹配组的数组。

let text_min = '2016-02-02 14:30';
let text_sec = '2016-02-02 14:30:34';
let text_ms = '2016-02-02 14:30:34.234';

function matchDateTime(text) { return text.match(/(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d)(?::(\d\d)(?:\.(\d\d\d))?)?/); }

function hasSeconds(text) { return !!matchDateTime(text)[6]; }
function hasMilliSeconds(text) { return !!matchDateTime(text)[7]; }

function testTimeString(text) {
console.log(text, "hasSeconds=", hasSeconds(text));
console.log(text, "hasMilliSeconds=", hasMilliSeconds(text));
}

testTimeString(text_min);
testTimeString(text_sec);
testTimeString(text_ms);

console.log(matchDateTime(text_ms));

关于javascript - 检查momentjs中日期文本是否有毫秒和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51867938/

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