Métodos comumente usados para obter conteúdo relacionado a datas

1. O método de formatação da data

//只返回日期(年-月-日)
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. O método de comparação do tamanho de dois pontos no tempo

// 比较两个时间点大小(本方法只含小时和分钟,且适合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
}

 Esse método é adequado para o cenário em que o horário de término não pode ser anterior ao horário de início se o horário for selecionado por autoatendimento no mesmo dia .

3. Obtenha o número de dias em um determinado mês (por exemplo, 31 em março)

// 第一个参数传的是日期
// 如果传第二个参数是'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. Obtenha a data de ontem ou de alguns dias atrás

// 昨天(前几天),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. Obtenha a data de amanhã ou dos próximos dias

// 明天(后几天),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)
}

Os métodos acima são todos métodos comumente usados ​​em meu desenvolvimento atual, registre-os primeiro e atualize-os mais tarde, quando houver novos! 

Acho que você gosta

Origin blog.csdn.net/JJ_Smilewang/article/details/130704135
Recomendado
Clasificación