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"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM