计算日期的一些方法
某个日期距离当前日期相差的天数
实现某个日期距离当前日期相差的天数,常用场景如:已知计划结束日期,计算剩余工期。
const getDiffDate = (targetDate) => {
let date1 = new Date(targetDate);
let date2 = new Date();
date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
const diff = date1.getTime() - date2.getTime(); //计算出相差的时间戳
const diffDate = diff / (24 * 60 * 60 * 1000); //计算相关的天数
return diffDate;
}
// 调用的地方,假设计划结束日期为2024-12-31,计算剩余工期
getDiffDate('2024-12-31');
获取当前时间
export function curTime() {
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
const hour = now.getHours().toString().padStart(2, '0');
const minute = now.getMinutes().toString().padStart(2, '0');
const second = now.getSeconds().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
获取近12小时的时间
export function last12H() {
const now = new Date();
const data = new Date(now.getTime() - 12 * 60 * 60 * 1000);
const year = data.getFullYear();
const month = (data.getMonth() + 1).toString().padStart(2, '0');
const day = data.getDate().toString().padStart(2, '0');
const hour = data.getHours().toString().padStart(2, '0');
const minute = data.getMinutes().toString().padStart(2, '0');
const second = data.getSeconds().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
获取近7天的时间
export function last7D() {
const now = new Date();
const data = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const year = data.getFullYear();
const month = (data.getMonth() + 1).toString().padStart(2, '0');
const day = data.getDate().toString().padStart(2, '0');
const hour = data.getHours().toString().padStart(2, '0');
const minute = data.getMinutes().toString().padStart(2, '0');
const second = data.getSeconds().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
本文介绍了一个JavaScript函数getDiffDate,用于计算给定日期(如2024-12-31)与当前日期之间的天数差,常用于工程管理中计算剩余工期。它通过新Date对象处理日期并进行时间戳计算。
2万+

被折叠的 条评论
为什么被折叠?



