首页 > 解决方案 > 如何使用javascript获取最近的十年/世纪/千年

问题描述

我试图找到一种方法来获取日期的 2 个最近范围可能是十年、世纪、千年

例子

var date = new Date() // Mon Jul 09 2018 17:12:17 GMT-0400
date.getDecadeRange() // [Jan 01 2010 , Dec 31 , 2019]

等等。

标签: javascriptdate

解决方案


为了四舍五入到最接近的倍数,我们可以使用小工具:

 const round = (n, to) => n - n % to;

现在我们只需要对这些年进行舍入,然后取第一天:

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}`);


推荐阅读