js实现年月日
获取当前年月日
使用 Date 对象可以轻松获取当前的年、月、日。以下是示例代码:
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1; // 月份从0开始,需要加1
const day = currentDate.getDate();
console.log(`当前日期:${year}-${month}-${day}`);
格式化年月日
如果需要将日期格式化为特定形式(如 YYYY-MM-DD),可以使用以下方法:
function 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}`;
}
const formattedDate = formatDate(new Date());
console.log(formattedDate); // 输出类似 "2023-10-05"
解析字符串为年月日
从字符串(如 "2023-10-05")解析为年、月、日:
const dateString = "2023-10-05";
const parts = dateString.split("-");
const year = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10);
const day = parseInt(parts[2], 10);
console.log(`年:${year}, 月:${month}, 日:${day}`);
计算两个日期的差值
计算两个日期之间的天数差:
function getDaysBetweenDates(date1, date2) {
const timeDiff = Math.abs(date2.getTime() - date1.getTime());
return Math.floor(timeDiff / (1000 * 60 * 60 * 24));
}
const startDate = new Date("2023-10-01");
const endDate = new Date("2023-10-05");
const daysDiff = getDaysBetweenDates(startDate, endDate);
console.log(`相差天数:${daysDiff}`);
添加或减少天数
在当前日期上添加或减少天数:
function addDays(date, days) {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
const today = new Date();
const futureDate = addDays(today, 7);
console.log(`一周后的日期:${formatDate(futureDate)}`);
使用第三方库(如 date-fns)
对于更复杂的日期操作,可以使用 date-fns 或 moment.js:
import { format, addDays } from 'date-fns';
const today = new Date();
const formatted = format(today, 'yyyy-MM-dd');
const nextWeek = addDays(today, 7);
console.log(`格式化日期:${formatted}`);
console.log(`一周后的日期:${format(nextWeek, 'yyyy-MM-dd')}`);
注意事项
- 月份从
0开始(0表示一月,11表示十二月),使用时需加1。 - 使用
padStart确保月份和日期的两位数格式。 - 处理时区问题时,建议使用
toISOString或第三方库。







