美文网首页
JS 常用时间转换

JS 常用时间转换

作者: 上帝说有bug | 来源:发表于2020-12-09 15:02 被阅读0次

    支持 年 月 日 时 分 秒 星期

    /**
     * Parse the time to string
     * @param {(Object|string|number)} time 时间对象 new Date()
     * @param {string} cFormat   '{y}-{m}-{d} {h}:{i}:{s} 星期{a}' 
     * @returns {string}   2020-10-10 12:00:00 星期一
     */
    function parseTime(time, cFormat) {
      if (arguments.length === 0) {
        return null
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    }
    

    支持显示 几小时前 几分钟前 刚刚

    /**
     * @param {number} time
     * @param {string} option
     * @returns {string}
     */
    function formatTime(time, option) {
      if (('' + time).length === 10) {
        time = parseInt(time) * 1000
      } else {
        time = +time
      }
      const d = new Date(time)
      const now = Date.now()
    
      const diff = (now - d) / 1000
    
      if (diff < 30) {
        return '刚刚'
      } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
      } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
      } else if (diff < 3600 * 24 * 2) {
        return '1天前'
      }
      if (option) {
        return parseTime(time, option)
      } else {
        return (
          d.getMonth() +
          1 +
          '月' +
          d.getDate() +
          '日' +
          d.getHours() +
          '时' +
          d.getMinutes() +
          '分'
        )
      }
    }
    

    相关文章

      网友评论

          本文标题:JS 常用时间转换

          本文链接:https://www.haomeiwen.com/subject/jfuhgktx.html