Angular 、TypeScript 2 : 获取当前日期及前后7、15、30天或某一范围的日期

前言

今天有个接口字段需求,要写一个今天及前几天的日期传过去;

在网上找了下都木有什么比较好的方案;就自己写了一个。

因为技术栈就是NG2+TS2+WEBPACK,这里的代码需要一定的TS2及ES6的基础

代码

/**
   * @param {number} range
   * @param {string} [type]
   * @memberOf VehicleOverviewComponent
   * @description 获取今天及前后天
   */
  getRangeDate( range: number, type?: string ) {

    const formatDate = ( time: any ) => {
      // 格式化日期,获取今天的日期
      const Dates = new Date( time );
      const year: number = Dates.getFullYear();
      const month: any = ( Dates.getMonth() + 1 ) < 10 ? '0' + ( Dates.getMonth() + 1 ) : ( Dates.getMonth() + 1 );
      const day: any = Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate();
      return year + '-' + month + '-' + day;
    };

    const now = formatDate( new Date().getTime() ); // 当前时间
    const resultArr: Array<any> = [];
    let changeDate: string;
    if ( range ) {
      if ( type ) {
        if ( type === 'one' ) {
          changeDate = formatDate( new Date().getTime() + ( 1000 * 3600 * 24 * range ) );
          console.log( changeDate );
        }
        if ( type === 'more' ) {
          if ( range < 0 ) {
            for ( let i = Math.abs( range ); i >= 0; i-- ) {
              resultArr.push( formatDate( new Date().getTime() + ( -1000 * 3600 * 24 * i ) ) );
              console.log( resultArr );
            }
          } else {
            for ( let i = 1; i <= range; i++ ) {
              resultArr.push( formatDate( new Date().getTime() + ( 1000 * 3600 * 24 * i ) ) );
              console.log( resultArr );
            }
          }

        }
      } else {
        changeDate = formatDate( new Date().getTime() + ( 1000 * 3600 * 24 * range ) );
        console.log( changeDate );
      }
    }
  }

调用及结果

  1. range参数支持正负数,里面也加了判断;
  2. type【为可选参数】有两种,一个是字符串one,一个是more;前者返回一个指定的日期;后者返回一个排序好的范围
    getRangeDate( -6 );// 结果:2017-02-09
    getRangeDate( -6, 'one' );// 结果:2017-02-09

    getRangeDate( -6, 'more' );
    // 结果
    // ["2017-02-09", "2017-02-10", "2017-02-11", "2017-02-12", "2017-02-13", "2017-02-14",                 
    "2017-02-15"]

总结

就是用时间戳进行换算,然后通过内置函数获取对应字段进行拼接,,这里没有带时分秒,有兴趣的可以加个可选参数把时分秒带上。。因为我这里不需要用到,所以我就没加进去了。。

结果集为数组,但不仅限于数组,也可以改成对象。。看你们喜欢啦

原文链接:TypeScript 2 : 获取当前日期及前后范围日期【Array】

猜你喜欢

转载自blog.csdn.net/qq_24309787/article/details/81069121