js 日期 格式化

Date 转 String

/**
 * 日期格式化 Date -> String
 * @param {string} fmt  yyyy-MM-dd HH:mm:ss
 * @param {Date} date
 * @returns {string}
 */
export function dateFormat(fmt, date) {
  if (!date) {
    date = new Date()
  }

  var o = {
    ‘M+‘: date.getMonth() + 1, // 月份
    ‘d+‘: date.getDate(), // 日
    ‘h+‘: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
    ‘H+‘: date.getHours(), // 小时
    ‘m+‘: date.getMinutes(), // 分
    ‘s+‘: date.getSeconds(), // 秒
    ‘q+‘: Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + ‘‘).substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp(‘(‘ + k + ‘)‘).test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((‘00‘ + o[k]).substr((‘‘ + o[k]).length)))
    }
  }

  return fmt
}

String 转 Date

dateStr = dateStr.replace(/-/g, ‘/‘)

let date = new Date(‘2018/05/12‘)  // 根据时间字符串 新建Date,Safari 不支持“2018-05-12”   

let date = new Date(‘2018/5/12 10:22:20‘)  // 时间字符串可以 是 年/月,年/月/日,  年/月/日 时:分:秒

let date = new Date(1601481600000)  // 根据毫秒数 新建Date 
``

js 日期 格式化

上一篇:Clusternet - 新一代开源多集群管理与应用治理项目


下一篇:安装nodejs二进制文件