js 实现日期
日期对象创建
使用 new Date() 创建当前日期对象:
const now = new Date(); // 获取当前日期和时间
指定日期创建:
const specificDate = new Date('2023-10-01'); // 通过字符串
const dateWithParams = new Date(2023, 9, 1); // 注意月份从0开始(9表示10月)
日期格式化
转换为本地字符串:

console.log(now.toLocaleDateString()); // 输出本地日期格式(如"2023/10/1")
console.log(now.toLocaleTimeString()); // 输出本地时间格式(如"14:30:00")
自定义格式化(手动拼接):
const formattedDate = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
// 输出类似 "2023-10-01"
日期计算
增减天数:

const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1); // 增加1天
计算日期差(毫秒数转天数):
const diffMs = new Date('2023-10-10') - new Date('2023-10-01');
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); // 结果为9天
日期比较
直接比较时间戳:
const isLater = new Date('2023-10-02') > new Date('2023-10-01'); // true
第三方库推荐
使用 date-fns 或 moment.js(已逐渐淘汰)简化操作:
import { format, addDays } from 'date-fns';
console.log(format(new Date(), 'yyyy-MM-dd')); // 格式化
console.log(addDays(new Date(), 7)); // 增加7天
注意事项
- 月份从
0开始(0表示一月)。 - 时区问题:
new Date(string)可能因浏览器不同解析结果有差异,建议使用YYYY-MM-DD格式。 - 性能敏感场景建议使用时间戳(
Date.now())而非日期对象。






