小编Wer*_*rek的帖子

如何将月份值从一个Date对象复制到另一个对象?

给定两个Date对象,如何将第一个对象的月份正确设置为另一个对象的月份?

我面临着将日期,月份和年份从一个Date对象复制到另一个对象的任务。复制日期和年份按预期工作,当我尝试复制月份时出现问题。

使用b.setMonth(a.getMonth())结果会使b的月份过多。

b.setMonth(a.getMonth() - 1)但是,使用会导致b的月份比要求的少一。

以下打字稿代码:

      let a = new Date(2018, 1, 12);
      let b = new Date();
      console.log(a);
      console.log(b);

      console.log('====');
      console.log(a.getMonth());
      console.log(b.getMonth());

      b.setMonth(a.getMonth());

      console.log('====');
      console.log(a.getMonth());
      console.log(b.getMonth());


      b.setMonth(a.getMonth() - 1);

      console.log('====');
      console.log(a.getMonth());
      console.log(b.getMonth());
Run Code Online (Sandbox Code Playgroud)

返回值:

Mon Feb 12 2018 00:00:00 GMT+0100
Thu Aug 29 2019 16:11:03 GMT+0200
====
1
7
====
1
2
====
1
0                  // 2 - 1 = 0 ?
Run Code Online (Sandbox Code Playgroud)

似乎2-1应该给1 (a.getMonth() - 1),但是显然Date对象的行为有所不同。在javascript / typescript中将月份从一个Date对象复制到另一个Date对象的正确方法是什么?我想将两个日期都转换为字符串,复制正确的字符,然后将字符串解析回Date可以,但是我想知道是否有一种更简单,更清洁的方法。

javascript typescript ionic-framework angular

9
推荐指数
2
解决办法
135
查看次数

标签 统计

angular ×1

ionic-framework ×1

javascript ×1

typescript ×1