JavaScript中的日期处理是一个常见但有时又令人头疼的任务。在这篇博客文章中,我将分享一些在JavaScript中处理日期时遇到的常见问题以及它们的解决方法。
日期格式化
1.1 日期格式:yyyy-MM-dd
formatDate() {
var value = new Date()
var year = value.getFullYear();
var month = value.getMonth() + 1;
var date = value.getDate()
if (date >= 1 && date <= 9) { // 日如果小于10就补个0
date = "0" + date;
}
if (month >= 1 && month <= 9) { // 月如果小于10就补个0
month = "0" + month;
}
console.log(year + '-' + month + '-' + date) // 打印出年 - 月 - 日
var time = year + '-' + month + '-' + date
return time
}
const formattedDate = this.formatDate();
console.log(formattedDate); // 输出类似 '2021-05-14' 的字符串
1.2 日期格式:yyyy-MM-dd HH:mm:ss
formatDate(date) {
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const date = new Date();
const formattedDate = this.formatDate(date);
console.log(formattedDate); // 输出类似 '2021-05-14 16:30:00' 的字符串
基于当前日期的计算
2.1 通过时间戳输出年月日
timestampToYearMonthDay(timestamp) {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以需要+1
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
2.2 获取当前日期的前一天或后一天
Var preDate = new Date().getTime() - 24*60*60*1000; // 前一天
Var nextDate = new Date().getTime() + 24*60*60*1000; // 后一天
// 获得时间戳:1717490977923
2.3 获取当前日期的上个月或下个月
/*
* 获取当前日期的上个月
* @date 格式为yyyy-mm-dd的日期,如:2014-01-25
*/
getPreMonth(date) {
var arr = date.split('-');
var year = arr[0]; // 获取当前日期的年份
var month = arr[1]; // 获取当前日期的月份
var day = arr[2]; // 获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); // 获取当前日期中月的天数
var year2 = year;
var month2 = parseInt(month) - 1;
if (month2 == 0) {
year2 = parseInt(year2) - 1;
month2 = 12;
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}
/*
* 获取当前日期的下个月
* @date 格式为yyyy-mm-dd的日期,如:2014-01-25
*/
getNextMonth(date) {
var arr = date.split('-');
var year = arr[0]; // 获取当前日期的年份
var month = arr[1]; // 获取当前日期的月份
var day = arr[2]; // 获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); // 获取当前日期中的月的天数
var year2 = year;
var month2 = parseInt(month) + 1;
if (month2 == 13) {
year2 = parseInt(year2) + 1;
month2 = 1;
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}
2.4 获取本周、本月、本年的开始和结束时间
getTimeRangeFormatted() {
const currentDate = new Date();
const currentDay = currentDate.getDay();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getFullYear();
// 获取本周的第一天和最后一天
const startOfWeek = new Date(currentDate);
startOfWeek.setDate(currentDate.getDate() - currentDay + (currentDay === 0 ? -6 : 1));
const endOfWeek = new Date(currentDate);
endOfWeek.setDate(startOfWeek.getDate() + 6);
// 获取本月的第一天和最后一天
const startOfMonth = new Date(currentYear, currentMonth, 1);
const endOfMonth = new Date(currentYear, currentMonth + 1, 0);
// 获取本年的第一天和最后一天
const startOfYear = new Date(currentYear, 0, 1);
const endOfYear = new Date(currentYear, 11, 31);
// 格式化日期为:YYYY-MM-DD
const formatDate = (date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
return {
thisWeek: { startDate: formatDate(startOfWeek), endDate: formatDate(endOfWeek) },
thisMonth: { startDate: formatDate(startOfMonth), endDate: formatDate(endOfMonth) },
thisYear: { startDate: formatDate(startOfYear), endDate: formatDate(endOfYear) }
};
}
使用:
const { thisWeek, thisMonth, thisYear } = this.getTimeRangeFormatted();
console.log(thisWeek, thisMonth, thisYear,'本周/本月/本年');
控制台输出:
相对日期范围与周期计算
3.1 获取输入日期几个月前或几个月后的具体日期
/**
*获取输入日期几个月前的具体日期
*{param:DateTime} date 输入日期(YYYY-MM-DD)
*{param:number } monthNum 月数
*/
GetPreMonthDay(date, monthNum) {
var dateArr = date.split('-');
var year = dateArr[0]; // 获取当前日期的年份
var month = dateArr[1]; // 获取当前日期的月份
var day = dateArr[2]; // 获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); // 获取当前日期中月的天数
var year2 = year;
var month2 = parseInt(month) - monthNum;
if (month2 <= 0) {
var absM = Math.abs(month2);
year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12);
month2 = 12 - (absM % 12);
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}
/*
*获取输入日期几个月后的具体日期
*{param:DateTime} date 输入日期(YYYY-MM-DD)
*{param:number } monthNum 月数
*/
GetNextMonthDay(date, monthNum) {
var dateArr = date.split('-');
var year = dateArr[0]; // 获取当前日期的年份
var month = dateArr[1]; // 获取当前日期的月份
var day = dateArr[2]; // 获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); // 获取当前日期中的月的天数
var year2 = year;
var month2 = parseInt(month) + parseInt(monthNum);
if (month2 > 12) {
year2 = parseInt(year2) + parseInt((parseInt(month2) / 12 == 0 ? 1 : parseInt(month2) / 12));
month2 = parseInt(month2) % 12;
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
},
3.2 通过年月去获取本月份第一天和最后一天日期
例如:
let datem = { month: 3, year: 2024 };
let { monthFirstday, monthLastday } = this.getFirstAndLastDay(datem);
输出 monthFirstday: 2024-03-01 , monthLastday: 2024-03-31
getFirstAndLastDay(datem) {
// 获取本月第一天
let firstDay = new Date(datem.year, datem.month - 1, 1);
// 获取下个月第一天
let nextMonthFirstDay = new Date(datem.year, datem.month, 1);
// 获取本月最后一天
let lastDay = new Date(nextMonthFirstDay - 1);
let monthFirstday = this.formatDate(firstDay)
let monthLastday = this.formatDate(lastDay)
return { monthFirstday, monthLastday };
},
3.3 计算两个日期之间相差多少天
formatDate(preTime,nextTime){
let nowtime = new Date(preTime).getTime()
let updatatime = new Date(nextTime).getTime()
let difftime = nowtime - updatatime
let day = parseInt(difftime/(1000*60*60*24))
return day
}
let differDate = this.formatDate("2023-10-11 11:35:11","2023-12-21 11:35:11")
console.log(differDate,'距离上次时间相差几天')
3.4 计算日期和月份的相加减
let data = 2025-11-06 // 日期
let num = 3 // 月份
//计算日期和月份的相加(日期 + 月份 = 日期)
CountTime(date, num) {
var monthnum = 0;
if (typeof (num) == "string")
monthnum = parseInt(num);
else
monthnum = num;
if (typeof (date) == "string")
date = new Date(date);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var sumMonths = month + monthnum;
var newyear = year + parseInt(sumMonths/12);
var newmonth = this.checkMonth(sumMonths % 12);
var newday = this.checkMonth(day);
if (newmonth < 1) {
if (newmonth == 0) newyear--;
newmonth =0- (sumMonths-1) % 12;
}
var da = new Date(newyear, newmonth, 0);
return newyear + "-" + newmonth + "-" + (da.getDate() < newday?da.getDate():newday);
},
//计算日期和月份的相减(日期 - 月份 = 日期)
SubTime(date, num) {
var monthnum = 0;
if (typeof (num) == "string")
monthnum = parseInt(num);
else
monthnum = num;
if (typeof (date) == "string")
date = new Date(date);
var Y = date.getFullYear();
var M = date.getMonth() + 1;
var D = this.checkMonth(date.getDate());
let H = parseInt(monthnum%12)
let y = parseInt(monthnum/12).toFixed(0)
if(H < M){
Y = Y - y
M = M - H
}else{
Y = Y - y - 1
M = 12 + M - H
}
var da = new Date(Y, M, 0);
let MM = this.checkMonth(M)
return Y + "-" + MM + "-" + (da.getDate() < D?da.getDate():D);
},
// 计算'月'、'日'前年加上0
checkMonth (i) {
if (i<10){
i = "0" + i;
}
return i;
},
总结
在本文中,我们深入探讨了JavaScript中日期处理的多个方面。从基本的日期格式化到复杂的日期计算和周期性日期范围的获取,我们提供了一系列的解决方案和示例代码。这些示例不仅展示了如何使用JavaScript的Date
对象来格式化和计算日期,而且还提供了实用的函数,以帮助开发者在实际项目中更高效地处理日期和时间。