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

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));

09-10 05:39
查看更多