Angular中关于时间的操作总结

创建时间

使用new Date(),可以看见有5种构造函数

new Date()

    console.log(new Date()); // 当前时间
    console.log(new Date('2015-08-12 12:30'));// 字符串
    console.log(new Date(12345679));//时间戳
    console.log(new Date(2018, 3, 20, 12, 30));//指定年月日等

结果

如果要创建一个时间为当日的日期不包含时间的值

 console.log(new Date(new Date().toLocaleDateString()));

结果

时间计算

通常可以转换成时间戳的方式进行计算

    const endTime = new Date(new Date().toLocaleDateString());
    let d = endTime.valueOf(); // 时间戳
    d -= 7 * 24 * 60 * 60 * 1000;
    const startTime = new Date(d);
    console.log(startTime);
    console.log(endTime);
    console.log(d);

image.png

时间转换

自身还是有很多方法可以使用的

    console.log(new Date().toTimeString());
    console.log(new Date().toLocaleDateString());
    console.log(new Date().toDateString());
    console.log(new Date().getTime());

和想要的有点不一样

Angular 自带的时间管道

<p>现在的时间是{{today | date:'yyyy-MM-dd HH:mm:ss'}}</p>

image.png

第三方插件

moment.js

这是一个很强大的时间插件,这里用一个应用场景来演示。

nodejs上的时间和我本地的时间总是相差8个小时,这导致我每次发送时间到后台时,nodejs将时间转化成字符串传送出去的时候总是和我服务器上的时间相差8小时。
node上显示出来时间
node上时间
本地系统显示时间
本地时间
发送前控制台打印出来
发送前控制台打印出来

浏览器网络中监测显示
浏览器网络中监测显示

解决方案

nodejs只有在发送时间类型的数据时会进行转换,导致相差8个小时,但是我发送前就将其转换成字符串,就不会造成这样的结果了。
所以对angular的http进行封装,在发送前将body中的时间类型转换成字符串类型

    post(url: string, body?: any, params?: any,headers?:any) {
        this.begin();
        return this.http
            .post(url, this.parseBody(body) || null, {
                headers:this.parseHeaders(headers),
                params: this.parseParams(params)
            })
    }
  parseBody(body: any) {
    if (body) {
      for (const key in body) {
        if (body[key]) {
          const _data = body[key];
          // 将时间转化为字符串
          if (moment.isDate(_data)) {
            body[key] = moment(_data).format('YYYY-MM-DD HH:mm:ss');
          }
        }
      }
    }
    return body;
  }

完美解决

其中用到了moment.js 的两个方法,一个时判断是否时时间类型moment.isDate(_data)另一个时转换成字符串moment(_data).format(‘YYYY-MM-DD HH:mm:ss’);
关于更多用法可以参考官网

猜你喜欢

转载自blog.csdn.net/yiershan1314/article/details/79999744