new Data()

135 阅读1分钟

1、 new Date() 标准格式

image.png

2、new Date() 是一个对象,对象中存在多种操作时间的方法

image.png

3、其它时间格式转为标准格式

image.png

注意事项:当为时间戳时,须为13位的number类型;当为普通格式时,须为字符串,其它格式转换报错;

4、时间格式处理常用方法

function formatData() {
    if (obj == null) {
        return null
    }
    let now = new Date();
    let year = now.getFullYear();
    let month = (now.getMonth() + 1).toString().padStart(2, "0");
    let date = (now.getDate()).toString().padStart(2, "0");
    let hh = (now.getHours()).toString().padStart(2, "0");
    let mm = (now.getMinutes()).toString().padStart(2, "0");
    let ss = (now.getSeconds()).toString().padStart(2, "0");
    return `${year}-${month}-${date} ${hh}:${mm}:${ss}`;
}

5、判断是否当天,当周等

const addZero = (m: number): (string | number) => {
  return m < 10 ? '0' + String(m) : String(m)
}

const isSameDay = (dateA: Date, dateB: Date): boolean => dateA.getFullYear() === dateB.getFullYear() &&
  dateA.getMonth() === dateB.getMonth() &&
  dateA.getDate() === dateB.getDate()

export const timeFormatMain = (time: number): string => {
  if (time) {
    const today = new Date()
    const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24)
    const start = new Date(new Date().toLocaleDateString()).getTime()
    const currentDay = today.getDay() === 0 ? 7 : today.getDay()
    const currentMonday = start - 1000 * 60 * 60 * 24 * (currentDay - 1)

    const timeDateIns = new Date(time)

    const timeYear = timeDateIns.getFullYear()
    const timeMonth = addZero(timeDateIns.getMonth() + 1)
    const timeDay = addZero(timeDateIns.getDate())
    const timeHour = addZero(timeDateIns.getHours())
    const timeMin = addZero(timeDateIns.getMinutes())
    const isSameYear = today.getFullYear() === timeYear

    if (isSameDay(timeDateIns, today)) {
      return `${timeHour}:${timeMin}`
    }
    if (isSameDay(timeDateIns, yesterday)) {
      return `昨天 ${timeHour}:${timeMin}`
    }
    if (time > currentMonday) {
      return `周${'日一二三四五六'.charAt(timeDateIns.getDay())} ${timeHour}:${timeMin}`
    }
    if (isSameYear) {
      return `${timeMonth}${timeDay}${timeHour}:${timeMin}`
    }
    return `${timeYear}${timeMonth}${timeDay}${timeHour}:${timeMin}`
  }
  return ''
}