JavaScript 获取日期范围
例如起始时间是 2021/02/01
获取下个月的日期, 结果应为 2022/02/01
.
代码描述:
const date = new Date("2021/02/01");
date.setMonth(date.getMonth() + 1);
复制代码
又如, 根据当前时间想获取下一年零两个月五天七时八分九秒的区间日期呢?
直接操作 Date
类那简直是天灾!
工具函数:
/**
* 获取日期范围
* @param date {Date}
* @param rule {String} [年(y)|月(M)|日(d)|时(h)|分(m)|秒(s)|毫秒(S)]
* @param direction {Number} [-1|1]
* @returns {Date}
* @exmaple
* getDateRange(Date.now(), "1y2M3d4h5m6s7S");
*/
function getDateRange(date, rule, direction = 1) {
const startDate = new Date(date);
const endDate = new Date(startDate);
const o = {
y: "FullYear",
M: "Month",
d: "Date",
h: "Hours",
m: "Minutes",
s: "Seconds",
S: "Milliseconds"
};
for (const key in o) {
const reg = new RegExp(`([0-9]+)${key}`);
const method = o[key];
if (reg.test(rule)) {
const match = rule.match(reg);
const num = match[1] >> 0;
const matchStr = match[0];
rule = rule.replace(matchStr, "");
endDate[`set${method}`](endDate[`get${method}`]() + num * direction);
}
}
return endDate;
}
复制代码
使用示例
const date = new Date("2021/03/01 10:10:10:100");
// 向后获取范围
getDateRange(date, "1y", 1); // (format) => "2022/03/01 10:10:10:100"
// 向前获取范围
getDateRange(date, "1y", -1); // (format) => "2020/03/01 10:10:10:100"
// 全部规则 [年(y)|月(M)|日(d)|时(h)|分(m)|秒(s)|毫秒(S)],默认向后获取
getDateRange(date, "1y"); // (format) => "2022/03/01 10:10:10:100"
getDateRange(date, "1M"); // (format) => "2021/04/01 10:10:10:100"
getDateRange(date, "1d"); // (format) => "2021/03/02 10:10:10:100"
getDateRange(date, "1h"); // (format) => "2021/03/01 11:10:10:100"
getDateRange(date, "1m"); // (format) => "2021/03/01 10:11:10:100"
getDateRange(date, "1s"); // (format) => "2021/03/01 10:10:11:100"
getDateRange(date, "1S"); // (format) => "2021/03/01 10:10:10:101"
// 组合规则
getDateRange(date, "1y2M3d4h5m6s7S"); // (format) => "2022/05/04 14:15:16:107"
复制代码
相关类库
- 成熟的日期处理类库 Moment.js
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END