如何在Typescript中获取当前日期前3个月的日期对象

时间:2021-01-06 02:31:43

标签: typescript date

我正在尝试像这样从当前日期起 3 个月之前获取日期对象。

toDate = new Date();
fromDate  = this.toDate.getMonth() - 3;

但是 fromDate 只是一个数字。每次我想从当前日期起 3 个月之前获取日期。但这仅显示了这样的选项。

this.fromDate = (this.toDate.getMonth() - 3).toLocaleString()

是否可以在 3 个月之前获取日期对象?

2 个答案:

答案 0 :(得分:1)

也许我能帮上忙

toDate = new Date();
month = toDate.getMonth() -3;
newDate = new Date(toDate.setMonth(month));

答案 1 :(得分:0)

您从 getMonth 获取数字的原因是它返回一个月的整数值或“索引”。一月是 0,十二月是 11。See the getMonth docs 了解更多详情。

要获得过去 3 个月的新日期,您应该使用内置的 Date setMonth 函数。

function monthsBackFrom(date: Date, n: number): Date {
  // Create a new date so the original is not modified
  const result = new Date(date);

  // Careful, setMonth modifies the date object in place
  result.setMonth(result.getMonth() - n); // Set to n months back from current
  return result;
}

const now = new Date();
const threeMonthsBack: Date = monthsBackFrom(now, 3);

console.log(now.toString()) // Current date and time
console.log(threeMonthsBack.toString()); // Date three months back, same time

请注意,setMonth 会就地修改您的日期。它不会创建新的日期。在设置 fromDate 时,您很可能需要创建一个新的 Date 对象,以便您的 toDate 不受影响。

setMonth 还支持负数和大于 12 的值。将月份设置为 -1 会将日期设置为上一年的十二月。将月份设置为 12 会将日期设置为下一年的一月*。日期和时间信息保持不变。

相关问题