1. 程式人生 > 其它 >vue 獲取當前時間的前一天 後一天 一週 或者是當前時間的幾個小時

vue 獲取當前時間的前一天 後一天 一週 或者是當前時間的幾個小時

一、在方法中寫入以下程式碼:

methods: {
   getDay (day, hours) {
      var today = new Date()
      var targetday = today.getTime() + 1000 * 60 * 60 * 24 * day + hours
      today.setTime(targetday)
      var tYear = today.getFullYear()
      var tMonth = today.getMonth()
      var tDate = today.getDate()
      var getHours = today.getHours()
      tMonth = this.doHandleMonth(tMonth + 1)
      tDate = this.doHandleMonth(tDate)
      return tYear + '-' + tMonth + '-' + tDate + '小時:' + getHours
    },
    doHandleMonth (month) {
      var m = month
      if (month.toString().length === 1) {
        m = '0' + month
      }
      return m
    },
   }

二、測試:

mounted () {
    console.log('昨天:', this.getDay(-1, 7200000))
    console.log('今天:', this.getDay(0, 3600000))
    console.log('明天:', this.getDay(1, 3600000))
    console.log('一週後:', this.getDay(7, 7200000)
 }

效果:

在這裡插入圖片描述