Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular中关于时间的操作总结大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

创建时间

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');关于更多用法可以参考官网

大佬总结

以上是大佬教程为你收集整理的Angular中关于时间的操作总结全部内容,希望文章能够帮你解决Angular中关于时间的操作总结所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: