Forum Discussion
JayCooper
3 years agoCommunity Member
JavaScript to Subtract Days from Current Date
I'm working on a course that involves sorting juveniles with one of the criteria being their age. I'm looking to display each child's age based on the current date, minus X number of days so that t...
Jürgen_Schoene_
3 years agoCommunity Member
here is a javascript example
const years = -18; // 18 years back
const days = +10; // 10 day forward
const event = new Date();
event.setFullYear(event.getFullYear() + years);
event.setDate(event.getDate() + days)
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
const result = event.toLocaleDateString('en-US', options);
// 'en-US' -> "Saturday, February 26, 2005"
// 'en-GB' -> "Saturday, 26 February 2005"
// 'de-DE' -> "Samstag, 26. Februar 2005"
more info for Date and toLocaleDateString
JayCooper
3 years agoCommunity Member
Jurgen,
Thank you for the help. The problem with breaking the new Date up this way is how to make adjustments if the date is at the beginning of the month or year.
I appreciate your help.
v/r
Jay
- Jürgen_Schoene_3 years agoCommunity Member
you have nothing to adjust - the javascript library does all adjustments automaticly,
this is modern JavaScriptconst years = -18; // 18 years back
const days = +10; // 10 day forward
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
const event = new Date( 'December 28, 2023 23:15:30');
console.log( "1 - now", event.toLocaleDateString('en-US', options) )
event.setFullYear(event.getFullYear() + years);
console.log( "2 - year", years, event.toLocaleDateString('en-US', options) )
event.setDate(event.getDate() + days)
console.log( "3 - days", days, event.toLocaleDateString('en-US', options) )result:
- "1 - now", "Thursday, December 28, 2023"
- "2 - year", -18, "Wednesday, December 28, 2005"
- "3 - days", 10, "Saturday, January 7, 2006"
or with February 29
const event = new Date( 'February 29, 2024 23:15:30');
console.log( "1 - now", event.toLocaleDateString('en-US', options) )
event.setFullYear(event.getFullYear() + years);
console.log( "2 - year", years, event.toLocaleDateString('en-US', options) )
event.setDate(event.getDate() + days)
console.log( "3 - days", days, event.toLocaleDateString('en-US', options) )result:
- "1 - now", "Thursday, February 29, 2024"
- "2 - year", -18, "Wednesday, March 1, 2006"
- "3 - days", 10, "Saturday, March 11, 2006"
or the same date, but -16 years - "1 - now", "Thursday, February 29, 2024"
- "2 - year", -16, "Friday, February 29, 2008"
- "3 - days", 10, "Monday, March 10, 2008"