javascript - 在 JS 中标准化时间的最佳方法

标签 javascript

我有一些不一致的数据。一切都与时间相关,但我有一些记录显示下午 3 点,其他记录显示14:00

有没有一种简单的方法可以在 JS 中标准化它?

谢谢

最佳答案

此函数将返回 24 小时格式的时间

function normaliseTime(time) {
    // If there is AM/PM in the string, do conversion
    if (time.toUpperCase().indexOf('M') >= 0) {
      // Remove the AM/PM text and split the hour and minute
      var tmArray = time.replace(/\D/g, '').split(':');
      // If PM, add 12 to the hour
      if (time.toUpperCase().indexOf('PM') >= 0) {
        tmArray[0] = parseInt(tmArray[0]) + 12;
      }
      // If minutes were not provided (i.e., 3PM), add 00 as minutes
      if (tmArray.length < 2) {
        tmArray[1] = '00';
      }
      return tmArray.join(':');
    }
    // If there was no AM/PM in the input, return it as is
    return time;
}

关于javascript - 在 JS 中标准化时间的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59832976/

相关文章:

javascript - 根据给定的点在矩形上设置 3 个对应点

javascript - Superagent 'request' 对象被重新定义为函数?

javascript - Mongoose - exec 函数有什么作用?

javascript - 如何在react js中的array.map上的事件onclick上添加函数

javascript - JQuery .hasClass 用于 if 语句中的多个值

javascript - 为什么这个带有 jQ​​uery tkey 属性的 JS 代码为不同语言提供不同的 html 字符串不起作用?

javascript - Secret 键盘上的隐藏信息 enter

javascript - 为什么在shouldComponentUpdate()中nextProps和this.props是相同的?

javascript - 异步图片加载

php - 配置 Emacs 以进行 Web 开发 (PHP)