更好用的JS的Date()封装函数time()

111 阅读2分钟

JavaScript 原生的Date()函数相当不好用,为此我们将Date()封装,得到更好用的time()函数,其中函数代码如下:

function time(...params){
  if (!(this instanceof time)) {
    return new time(...params)
  } //当调用时,没有加new时,前面加个new
  
  if (arguments.length > 1) { //arguments.length表示传入的实际参数的个数
    params[1] -= 1  //传入的第二个参数是月份,因为原生的date()函数是从0开始的,所以此处减一,以符合该函数的使用范围
  }
  
  this.date = new Date(...params)//把所有参数打个包,命名为数组,数组第0项表示第一个参数,然后将参数传进来
}

time.prototype = { //使用原型的方法来构造新函数
  constructor: time,
  parts(attrs) {
    if (attrs === undefined) {
      return {
        year: this.date.getFullYear(),
        month: this.date.getMonth() + 1,//date()函数中得到的月份是从0开始的
        day: this.date.getDate(),
        weekday: this.date.getDay(),//表示星期几,范围是0~6
        hour: this.date.getHours(),
        minute: this.date.getMinutes(),
        second: this.date.getSeconds(),
        ms: this.date.getMilliseconds()
      }
    } else {
      const { year, month, day, hour, minute, second, ms } = attrs
      year !== undefined && this.date.setFullYear(year)
      month !== undefined && this.date.setMonth(month - 1)
      day !== undefined && this.date.setDate(day)
      hour !== undefined && this.date.setHours(hour)
      minute !== undefined && this.date.setMinutes(minute)
      second !== undefined && this.date.setSeconds(second)
      ms !== undefined && this.date.setMilliseconds(ms)
    }
  },
  
  add(n, unit) { //传入增加的数目和单位
    const valid = 'year month day hour minute second ms'.split(' ').includes(unit)
    if (!valid) { // 防御性编程
      throw new Error('你传了一个什么单位,我不认识: ' + unit)
    }
    const table = {
      ms: 1,
      second: 1000,
      minute: 1000 * 60,
      hour: 1000 * 60 * 60,
      day: 1000 * 60 * 60 * 24,
    }
    if (unit === 'year') {
      this.date.setFullYear(this.date.getFullYear() + n)
    } else if (unit === 'month') {
      this.date.setMonth(this.date.getMonth() + n)
    } else { // 加上对应的毫秒数
      this.date = new Date(this.date - 0 + table[unit] * n)
    }// this.date - 0的操作是为了将这个字符串变成数字
  },
  
  isLeapYear() {//判断是不是闰年
    const year = this.date.getFullYear()
    if (year % 4 === 0) {
      if (year % 100 === 0) {
        if (year % 400 === 0) {
          return true
        } else {
          return false
        }
      } else {
        return true
      }
    } else {
      return false
    }
  },
  
  lastDayOfMonth() {//输出这个月的最后一天
    const { year, month, hour, minute, second, ms } = this.parts()
    return new time(year, month + 1, 0, hour, minute, second, ms)
  },//是直接设置为下个月的0号,相当于当月的最后一天
  format(pattern) { //输出自定义中文的时间表达形式
    // 支持的占位符有 yyyy MM dd HH mm ss
    const { year, month, day, hour, minute, second } = this.parts()
    return pattern.replace(/yyyy/g, year)
      .replace(/MM/g, padLeftZero(month))
      .replace(/dd/g, padLeftZero(day))
      .replace(/HH/g, padLeftZero(hour))
      .replace(/mm/g, padLeftZero(minute))
      .replace(/ss/g, padLeftZero(second))
  }
}

function padLeftZero(n) {   //在时间位数不够前面补足0
  return n > 10 ? '' + n : '0' + n
}