js实现年月日
获取当前年月日
使用 Date 对象获取当前年月日信息:
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1; // 月份从0开始,需加1
const day = date.getDate();
console.log(`${year}-${month}-${day}`);
格式化年月日
自定义格式化函数,确保月份和日期为两位数:

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}`;
}
console.log(formatDate(new Date()));
解析字符串为年月日
将日期字符串转换为 Date 对象并提取年月日:

const dateStr = '2023-05-15';
const date = new Date(dateStr);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
console.log(`${year}-${month}-${day}`);
计算两个日期之间的天数差
计算两个日期之间的天数差异:
function getDayDiff(date1, date2) {
const diffTime = Math.abs(date2 - date1);
return Math.floor(diffTime / (1000 * 60 * 60 * 24));
}
const startDate = new Date('2023-01-01');
const endDate = new Date('2023-01-10');
console.log(getDayDiff(startDate, endDate));
使用第三方库处理日期
使用 moment.js 或 date-fns 简化日期操作:
// 使用 moment.js
const moment = require('moment');
const date = moment();
console.log(date.format('YYYY-MM-DD'));
// 使用 date-fns
const { format } = require('date-fns');
console.log(format(new Date(), 'yyyy-MM-dd'));






