Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

How to get date object prior 3 months from current date in Typescript

I am trying to get the date object before 3 months from current date like this.

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

But fromDate is coming as just a number. Every time i want to get the date before 3 months from current date. But this shows only a option like this.

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

Is it possible to get the date object before 3 months?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason you are getting a number from getMonth is because it returns the integer value, or "index", of a month. January is 0, December is 11. See the getMonth docs for more details.

To get a new Date 3 months in the past, you should use the built in Date setMonth function.

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

Note that setMonth modifies your date in place. It does not create a new one. You will most likely need to create a new Date object when setting fromDate so your toDate is not affected.

setMonth also supports negatives and values greater than 12. Setting the month to -1 will set the date to December of the previous year. Setting the month to 12 will set the date to January of the next year*. Day and time information remains the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...