常用的获取日期相关内容的方法

1.格式化日期的方法

//只返回日期(年-月-日)
const formateDate = (val) => {
  const date = new Date(val)
  const year = date.getFullYear()
  const month = repairZero(date.getMonth() + 1)
  const day = repairZero(date.getDate())
  return `${year}-${month}-${day}`
}

// 返回日期+时间(年-月-日 时:分:秒)
const formateTime = (val) => {
  const date = new Date(val)
  const year = date.getFullYear()
  const month = repairZero(date.getMonth() + 1)
  const day = repairZero(date.getDate())
  const h = repairZero(date.getHours())
  const m = repairZero(date.getMinutes())
  const s = repairZero(date.getSeconds())
  return `${year}-${month}-${day} ${h}:${m}:${s}`
}


// 补0方法
const repairZero = (n) => {
  return ('' + n).length > 1 ? n : '0' + n
}

2.两个时间点比较大小的方法

// 比较两个时间点大小(本方法只含小时和分钟,且适合24小时制),如11:20 和 13:42 进行比较,如果前者比后者小或等于则返回true,否则返回false
const compareTime = (time1, time2) => {
  const timeBegin = time1.split(':')[0] * 60 * 60 + time1.split(':')[1] * 60
  const timeEnd = time2.split(':')[0] * 60 * 60 + time2.split(':')[1] * 60
  let flag = false
  if (timeBegin <= timeEnd) {
    flag = true
  } else {
    flag = false
  }
  return flag
}

 该方法适合于:自助选择时间时,若是同一天,则结束时间不能早于开始时间这样的场景。

3.获取某一月份的天数 (如3月则为31)

// 第一个参数传的是日期
// 如果传第二个参数是'day',得到的就是该月的天数,如果不传或传其他值,则得到的是对应的年月
// 注意这里的formateTime方法使用的就是上面第一条写的formateTime方法,这里就不赘述了
const getPreMonth = (date, type) => {
  const newDate = formateTime(date)
  const arr = newDate.split('-')
  const year = arr[0]  //获取当前日期的年份
  const month = arr[1] //获取当前日期的月份
  let days = new Date(year, month, 0)
  days = days.getDate() //获取当前日期中月的天数
  const t2 = year + '-' + month
  return type == 'day' ? days : t2 
}
console.log(getPreMonth('2021-4-10', 'day'))  // 输出30
console.log(getPreMonth('2023-5-1'))  // 输出2023-05

4.获取昨天或者前几天的日期

// 昨天(前几天),formateDate方法即为第一条所述方法
// 获取昨天日期无需传参,获取前天则传2,大前天传3,以此类推
const getPreDate = (n = 1) => {
  const date = new Date()
  const preDate = new Date(date.getTime() - n * 24 * 60 * 60 * 1000)
  return formateDate(preDate)
}

5.获取明天或者后几天的日期

// 明天(后几天),formateDate方法即为第一条所述方法
// 获取明天日期无需传参,获取后天则传2,大后天传3,以此类推
const getNextDate = (n = 1) => {
  const date = new Date()
  const nextDate = new Date(date.getTime() + n * 24 * 60 * 60 * 1000)
  return formateDate(nextDate)
}

以上这些方法,都是我在实际开发中常用方法,先记录下,后期有新的再更新! 

猜你喜欢

转载自blog.csdn.net/JJ_Smilewang/article/details/130704135
今日推荐