Javascript 日期相关计算
1、获取当前日期的前一天
// 获取当前日期
let today = new Date();
today.setDate(today.getDate() - 1);
// 转换为本地日期字符串格式
let yesterdayStr = today.toISOString().slice(0, 10);
console.log(yesterdayStr); // 例如: "2023-04-03" (格式取决于地区设置)
2、获取当前日期的上个礼拜的开始时间和结束时间
const today = new Date();
const dayOfWeek = today.getDay(); // 获取今天是周几,0(周日)到6(周六)
const diffDays = today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // 如果今天是周日,则diffDays为-6,否则为1,用于计算上周一
const monday = new Date(today.setDate(diffDays)); // 上周一的日期
const lastWeekEnd = new Date(monday); // 上周的结束日(周日)
lastWeekEnd.setDate(lastWeekEnd.getDate() - 1); // 上上周的结束日(周日的前一天)
const lastWeekStart = new Date(monday); // 上周的结束日(周日)
lastWeekStart.setDate(lastWeekStart.getDate() - 7); // 上上周的结束日(周日的前一天)
console.log("上上周结束日期:", lastWeekEnd.toISOString().slice(0, 10)); // ISO格式,去掉时间部分
console.log("上上周开始日期:", lastWeekStart.toISOString().slice(0, 10)); // ISO格式,去掉时间部分
3、获取当前日期的上个月的开始时间和结束时间
const today = new Date();
let lastMonth = new Date(today);
// 设置日期为当前月份的上一个月
lastMonth.setMonth(lastMonth.getMonth() - 1);
// 设置日期为上个月的第一天(即月初)
lastMonth.setDate(1);
// 获取上个月的第一天
const startOfLastMonth = lastMonth;
// 设置日期为下一个月的第一天,从而得到上个月的最后一天
const endOfLastMonth = new Date(lastMonth);
endOfLastMonth.setMonth(endOfLastMonth.getMonth() + 1);
endOfLastMonth.setDate(0); // 这会将日期设置为上个月最后一天
// 格式化日期为"YYYY-MM-DD"格式的字符串
const startDateStr = startOfLastMonth.toISOString().split("T")[0]; // 或者使用 toLocaleDateString('zh-CN') 并自定义格式化选项
const endDateStr = endOfLastMonth.toISOString().split("T")[0]; // 或者使用 toLocaleDateString('zh-CN') 并自定义格式化选项
console.log('上个月的开始时间',startDateStr)
console.log('上个月的结束时间',endDateStr)
4、JavaScript 中的日期对象
// 创建当前日期和时间的 Date 对象
const currentDate = new Date();
// 通过指定年、月、日、时、分、秒来创建 Date 对象
// 注意:月份是从 0 开始计数的,即 0 表示 1 月,11 表示 12 月
const specificDate = new Date(2024, 10, 15, 12, 30, 0);
// 通过日期字符串创建 Date 对象
const dateFromString = new Date('2024-11-15T12:30:00');
Date 对象提供了一系列方法来获取和设置日期与时间的各个部分,例如:
const date = new Date();
const year = date.getFullYear(); // 获取年份
const month = date.getMonth() + 1; // 获取月份(注意要加 1)
const day = date.getDate(); // 获取日期
const hours = date.getHours(); // 获取小时
const minutes = date.getMinutes(); // 获取分钟
const seconds = date.getSeconds(); // 获取秒数
5、 计算两个日期之间的天数
计算两个日期之间的天数是一个常见的需求。基本思路是先获取两个日期的时间戳(从 1970 年 1 月 1 日 00:00:00 UTC 到指定日期的毫秒数),然后计算它们的差值,最后将差值转换为天数。
function getDaysBetweenDates(startDate, endDate) {
const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
const firstDate = new Date(startDate).getTime();
const secondDate = new Date(endDate).getTime();
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
return diffDays;
}
const start = '2024-11-01';
const end = '2024-11-10';
const days = getDaysBetweenDates(start, end);
console.log(`两个日期之间相差 ${days} 天。`);
6、计算两个日期之间的月数和年数
计算两个日期之间的月数和年数相对复杂一些,需要考虑月份和年份的变化。
function getMonthsBetweenDates(startDate, endDate) {
const start = new Date(startDate);
const end = new Date(endDate);
let months;
months = (end.getFullYear() - start.getFullYear()) * 12;
months -= start.getMonth();
months += end.getMonth();
return months <= 0 ? 0 : months;
}
function getYearsBetweenDates(startDate, endDate) {
const start = new Date(startDate);
const end = new Date(endDate);
return end.getFullYear() - start.getFullYear();
}
const months = getMonthsBetweenDates(start, end);
const years = getYearsBetweenDates(start, end);
console.log(`两个日期之间相差 ${months} 个月。`);
console.log(`两个日期之间相差 ${years} 年。`);
7、判断某个日期是否在指定区间内
判断某个日期是否在指定的日期区间内,可以通过比较该日期的时间戳与区间两端日期的时间戳来实现。
function isDateInRange(date, startDate, endDate) {
const target = new Date(date).getTime();
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
return target >= start && target <= end;
}
const testDate = '2024-11-05';
const isInRange = isDateInRange(testDate, start, end);
console.log(`${testDate} 是否在 ${start} 到 ${end} 的区间内:${isInRange}`);
8、实际应用案例:酒店预订日期检查
在酒店预订系统中,需要检查用户选择的日期是否在可预订的日期区间内,并且计算预订的天数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>酒店预订日期检查</title>
</head>
<body>
<label for="startDate">入住日期:</label>
<input type="date" id="startDate">
<label for="endDate">退房日期:</label>
<input type="date" id="endDate">
<button onclick="checkBooking()">检查预订</button>
<p id="result"></p>
<script>
function getDaysBetweenDates(startDate, endDate) {
const oneDay = 24 * 60 * 60 * 1000;
const firstDate = new Date(startDate).getTime();
const secondDate = new Date(endDate).getTime();
const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
return diffDays;
}
function isDateInRange(date, startDate, endDate) {
const target = new Date(date).getTime();
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
return target >= start && target <= end;
}
function checkBooking() {
const start = document.getElementById('startDate').value;
const end = document.getElementById('endDate').value;
const availableStart = '2024-11-01';
const availableEnd = '2024-11-30';
if (isDateInRange(start, availableStart, availableEnd) && isDateInRange(end, availableStart, availableEnd)) {
const days = getDaysBetweenDates(start, end);
document.getElementById('result').textContent = `预订成功!您预订了 ${days} 天。`;
} else {
document.getElementById('result').textContent = '抱歉,您选择的日期不在可预订区间内。';
}
}
</script>
</body>
</html>
9、注意事项
- 时区问题:JavaScript 的
Date
对象在处理日期和时间时会受到本地时区的影响。如果需要处理跨时区的日期,建议使用Intl.DateTimeFormat
或者第三方库(如moment.js
、day.js
)。 - 日期格式:在使用日期字符串创建
Date
对象时,要确保日期格式符合标准,否则可能会导致Date
对象创建失败。
总结
JavaScript 的 Date
对象为我们提供了处理日期和时间的基本能力,通过合理运用其方法和属性,我们可以实现各种日期区间计算的需求。在实际开发中,根据具体业务场景选择合适的计算方法,并注意处理时区和日期格式等问题。同时,对于复杂的日期处理需求,也可以考虑使用第三方库来简化开发过程。希望本文能帮助你更好地掌握 JavaScript 中的日期区间计算。
整理不易,欢迎大家一键三连哦!😯