根据时间戳获取日期格式

1,105 阅读1分钟

在开发过程中,我们经常会用到各种的日期格式,如‘2020-05-07’、‘2020年5月7日’、‘2020年5月7日 15:52:47’等等的日期格式要求,一个个的写肯定问题不大,但是如果我们每次用到都要去写一遍这个方法的话,那么我们就会浪费很多的时间,所以我们这里把这个方法进行封装一下。

export class Tools{
  /**
   * @param timestamp 时间戳  ms
   * @param formats 时间格式 Y M D h m s
   * */
  public static getDate(timestamp:number, formats: string = 'Y-M-D'):string {
    let date = timestamp ? new Date(timestamp) : new Date();
    let year = date.getFullYear();
    let month = this.add0(date.getMonth() + 1);
    let day = this.add0(date.getDate());
    let hour = this.add0(date.getHours());
    let minute = this.add0(date.getMinutes());
    let second = this.add0(date.getSeconds());

    return formats.replace(/Y|M|D|h|m|s/ig, function (matches:string) {
      let result: any = {
        Y : year,
        M : month,
        D : day,
        h : hour,
        m : minute,
        s : second
      };
      return result[matches];
    })
  }
  /**
   * @param value 传入值
   * */
  private static add0(value:string|number):string {
    value = Number(value)
    return value < 10 ? '0' + value : value + ''
  }
}
// 调用的话就用Tools.getDate(Date.parse(new Date()), 'Y-M-D h:m:s')时间格式可自定义