js日期实现
日期对象创建
使用 new Date() 创建当前时间的日期对象:
const now = new Date();
通过指定参数创建特定日期:
const specificDate = new Date(2023, 11, 31); // 月份从0开始(11代表12月)
const dateFromString = new Date("2023-12-31T00:00:00");
日期获取方法
获取日期各组成部分:
const year = now.getFullYear();
const month = now.getMonth() + 1; // 0-11需要+1
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
const milliseconds = now.getMilliseconds();
const dayOfWeek = now.getDay(); // 0(周日)到6(周六)
日期设置方法
修改日期组成部分:
now.setFullYear(2024);
now.setMonth(6); // 7月
now.setDate(15);
now.setHours(14);
now.setMinutes(30);
日期格式化
转换为本地字符串:

now.toLocaleDateString(); // "2023/12/31"
now.toLocaleTimeString(); // "14:30:00"
now.toLocaleString(); // "2023/12/31 14:30:00"
自定义格式化函数:
function formatDate(date) {
return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`;
}
日期计算
时间戳计算(毫秒数):
const timestamp = now.getTime();
const tomorrow = new Date(timestamp + 86400000); // 加1天
使用日期差值:

const date1 = new Date(2023, 0, 1);
const date2 = new Date(2023, 11, 31);
const diffDays = Math.round((date2 - date1) / (1000 * 60 * 60 * 24));
时区处理
UTC方法(忽略本地时区):
const utcHours = now.getUTCHours();
now.setUTCHours(12);
转换为ISO格式:
const isoString = now.toISOString(); // "2023-12-31T06:30:00.000Z"
日期库推荐
对于复杂操作推荐使用第三方库:
- Moment.js(传统选择,已停止更新)
- date-fns(模块化现代库)
- Day.js(轻量级Moment替代品)
- Luxon(更强大的时区处理)






