JS - 倒计时 & 日期计算

倒计时

let timer = setInterval(() => {
  let now = new Date().getTime()
  this.countDown(now)
}, 1000)

function countDown(now) {
  let day11 = new Date(2019, 10, 11).getTime()
  
  if (day11 <= now) {
    console.log('活动结束~')
    clearInterval(timer)
    return
  }

  let interval = (day11 - now) / 1000
  let d = Math.floor(interval / (24 * 3600))
  let temp1 = interval - d * 24 * 3600
  let h = String(Math.floor(temp1 / 3600)).padStart(2, '0')
  let temp2 = temp1 - h * 3600
  let m = String(Math.floor(temp2 / 60)).padStart(2, '0')
  let s = String(Math.floor(temp2 - m * 60)).padStart(2, '0')
  
  console.log(`${d} 天 ${h} 时 ${m} 分 ${s} 秒`)
}

获取日期

/* 
  @method GetTime  获取日期信息

  @params {number} 可传入指定年月份
  
  @return 返回年、月、日、月份总天数、一号星期几
*/
function GetTime(_year, _month) {
  let date = !_year ? new Date() : new Date(_year, _month)
  
  const year = date.getFullYear() // 年
  const month = date.getMonth()   // 月
  const today = date.getDate()    // 日
  const days = new Date(year, month + 1, 0).getDate() // 月份总天数
  const firstDay = new Date(year, month, 1).getDay()  // 一号星期几
  
  return {
    year,
    month: String(month + 1).padStart(2, '0'),
    today: String(today).padStart(2, '0'),
    days,
    firstDay
  }
}

获取当前日期 & 时间:小程序官方实例(util.js)

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  formatTime: formatTime
}
发布了93 篇原创文章 · 获赞 20 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/sinat_33184880/article/details/102949920