Reputation: 833
im trying to find a way to get the 2 nearest ranges of a date could be decade , century, millenium
Example
var date = new Date() // Mon Jul 09 2018 17:12:17 GMT-0400
date.getDecadeRange() // [Jan 01 2010 , Dec 31 , 2019]
And so on.
Upvotes: 1
Views: 1969
Reputation: 138457
To round to the closest multiple we might use small utility:
const round = (n, to) => n - n % to;
Now we just have to round the years, and take the first day:
const round = (n, to) => n - n % to;
const now = new Date();
const start = new Date(round(now.getFullYear(), 100), 0, 1);
// Go to the start of the next period ...
const end = new Date(round(now.getFullYear(), 100) + 100, 0, 1);
end.setDate(end.getDate() - 1); // then go one day back
console.log(`${start}\n${end}`);
Upvotes: 4
Reputation: 833
Thanks everyone who answered. reading the jonas answer i had a momento and it came up to me the answer
const dateRanges = (date, rule, sum = 0)
=> Math.floor(date.getFullYear() / rule) * rule + sum
And i can execute it in this way
const lowerDecade = dateRanges(new Date() , 10 /** => decade**/)
const upperDecade = dateRanges(new Date() , 10 /** => decade**/, 9)
Upvotes: 1