JS获取当前时间的前一个小时及格式化时间

一、当前时间的前一个小时

  var frontOneHour = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
  console.log(new Date(new Date().getTime() - 1 * 60 * 60 * 1000), new Date()) // 前一个小时  当前时间
  console.log(frontOneHour)

二、格式化时间

// js
 function frontOneHour (fmt) {
    var currentTime = new Date(new Date().getTime())
    console.log(currentTime) // Wed Jun 20 2018 16:12:12 GMT+0800 (中国标准时间)
    var o = {
      'M+': currentTime.getMonth() + 1, // 月份
      'd+': currentTime.getDate(), // 日
      'h+': currentTime.getHours(), // 小时
      'm+': currentTime.getMinutes(), // 分
      's+': currentTime.getSeconds(), // 秒
      'q+': Math.floor((currentTime.getMonth() + 3) / 3), // 季度
      'S': currentTime.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (currentTime.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
  }
// 调用
frontOneHour('yyyy-MM-dd hh:mm:ss') // "2018-06-20 16:11:59"
frontOneHour('yyyy-MM-dd') // "2018-06-20"
frontOneHour('yyyyMMDD') // "201806DD"

猜你喜欢

转载自blog.csdn.net/yan263364/article/details/80748829