在TypeScript或Angular4+中计算历史日期及90天前日期的问题解决
Hey there! Let's break down your two date calculation questions for TypeScript and Angular 4+ clearly, with fixes for the issue you ran into.
Working with dates in TypeScript/Angular is straightforward once you get the hang of the native Date object methods. Here are common scenarios with code examples:
- Yesterday's date: Subtract 1 from the current day
const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); console.log(yesterday); // Outputs the date for one day ago - One week ago: Subtract 7 days
const oneWeekAgo = new Date(); oneWeekAgo.setDate(oneWeekAgo.getDate() - 7); - One month ago: Use
setMonth(note: this handles month-end edge cases automatically, like March 31 → February 28/29)const oneMonthAgo = new Date(); oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1); - Custom historical date: Combine methods for specific offsets, e.g., 2 years and 3 days ago
const customDate = new Date(); customDate.setFullYear(customDate.getFullYear() - 2); customDate.setDate(customDate.getDate() - 3);
TypeScript will infer the Date type automatically, but you can explicitly declare it if needed:
const historicalDate: Date = new Date(); historicalDate.setMonth(historicalDate.getMonth() - 3);
setMonth Issue) First, let's address the 90-day calculation—using setDate is the most reliable way here, since 90 days doesn't map cleanly to fixed months:
const ninetyDaysAgo: Date = new Date(); ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90); console.log(ninetyDaysAgo); // Correctly shows the date exactly 90 days prior
Now, about the issue with new Date().setMonth(new Date().getMonth() - 6): The problem here is that setMonth returns a timestamp (number of milliseconds since epoch), not a modified Date object. If you're trying to assign this directly to a variable, you'll end up with a number instead of a date.
Here's the fixed approach—always create a Date instance first, then modify it:
// Wrong: Assigns a timestamp number to sixMonthsAgo // const sixMonthsAgo = new Date().setMonth(new Date().getMonth() - 6); // Correct: Modify the Date instance after creating it const sixMonthsAgo: Date = new Date(); sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
Another edge case to watch for: If the current date is the 31st and the target month doesn't have 31 days (e.g., May 31 → November 31, but November only has 30 days), the Date object will automatically adjust to the last valid day of the target month (November 30 in this example). If you need strict "same day of month" behavior, you'll need to add extra checks, but this automatic adjustment is usually desired.
If you're working with UTC dates (to avoid timezone discrepancies), use the UTC-specific methods:
const ninetyDaysAgoUTC: Date = new Date(); ninetyDaysAgoUTC.setUTCDate(ninetyDaysAgoUTC.getUTCDate() - 90);
内容的提问来源于stack exchange,提问作者Shriyansh Jain

