js获取当前日期时间的前xxx时间及格式化时间

获取现在时间和开始时间的差

一、当前时间前15钟的日期

//获取xxx分钟前的时间日期
function timeFormat(minute) {
  //60000毫秒 代表1分钟
  let state = new Date(new Date().getTime() - minute * 60000),
      date = new Date(state),
      minutes = date.getMinutes()
  minutes < 0 ? minutes = `0${minutes}` : minutes = minutes
  //转换格式
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${minutes}`
}
console.log(timeFormat(15), '当前日期的前15分钟') //2022/10/28 23:55

二、当前时间前一个小时日期

//获取xxx小时前的时间日期
function timeFormat(hour) {
  let state = new Date(new Date().getTime() - hour * 60 * 60 * 1000),
    date = new Date(state),
	minutes = date.getMinutes()
  minutes < 0 ? minutes = `0${minutes}` : minutes = minutes
  //转换格式
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${minutes}`
}
console.log(timeFormat(1), '当前日期的前1个小时') 2022/10/28 23:15

到此结束。

猜你喜欢

转载自blog.csdn.net/weixin_43743175/article/details/127581419