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

标签 javascript momentjs

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

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/

相关文章:

javascript - 无法检测空段落

javascript - 如何为我的代码编写测试用例

javascript - 时刻.js : only certain localizations

javascript - 如何使用 moment.js 将多个日期转换为 JSON 对象为自定义格式的日期?

javascript - 集成 Moment JS 库时出现编码问题

javascript - Vue.js 组件点击事件找不到方法

javascript - 为什么我无法删除在 Electron 中使用 fs-extra 创建的目录?

angularjs - Moment.js 未捕获的语法错误

javascript - 如何让登录按钮在点击后变成下拉菜单

javascript - moment.duration 字符串给出 nan 值