I would like to subtract days from the current date in TypeScript. For example, if the current date is October 1st, 2017, I would like to subtract 1 day to get September 30th, 2017, or if I want to subtract 3 days I would get September 28th etc.
This is what I have so far, the result is I received December 31st, 1969. Which I assume means that tempDate.getDate() is returning zero, as in the Epoch of January 1, 1970.
This is my code, the goal is to return the previous working day.
protected generateLastWorkingDay(): Date {
var tempDate = new Date(Date.now());
var day = tempDate.getDay();
//** if Monday, return Friday
if (day == 1) {
tempDate = new Date(tempDate.getDate() - 3);
} else if (1 < day && day <= 6) {
tempDate = new Date(tempDate.getDate() - 1);
}
return tempDate;
}
getDate
returns the date of the month (1-31), so creating a new Date
from it treats that number as "milliseconds since epoch".
What you probably want is to use setDate
to change the date as it automatically handled going backwards through months/years.
protected generateLastWorkingDay(): Date {
const lastWorkingDay = new Date();
while(!this.isWorkingDay(lastWorkingDay)) {
lastWorkingDay.setDate(lastWorkingDay.getDate()-1);
}
return lastWorkingDay;
}
private isWorkingDay(date: Date) {
const day = date.getDay();
const isWeekday = (day > 0 && day < 6);
return isWeekday; // && !isPublicHoliday?
}
This is how I did
let yesterday=new Date(new Date().getTime() - (1 * 24 * 60 * 60 * 1000));
let last3days=new Date(new Date().getTime() - (3 * 24 * 60 * 60 * 1000));
We need to minus (no_of_days) * 24 * 60 * 60 * 1000
from current date.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With