加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular中关于时间的操作总结

发布时间:2020-12-17 08:18:16 所属栏目:安全 来源:网络整理
导读:创建时间 使用new Date(),可以看见有5种构造函数 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));//指定年月日等 如果要创

创建时间

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

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);

时间转换

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>

第三方插件

moment.js

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

nodejs上的时间和我本地的时间总是相差8个小时,这导致我每次发送时间到后台时,nodejs将时间转化成字符串传送出去的时候总是和我服务器上的时间相差8小时。
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');关于更多用法可以参考官网

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读