js 实现日期
日期对象创建
使用 new Date() 创建当前日期对象:
const now = new Date(); // 获取当前日期和时间
指定日期创建:
const specificDate = new Date('2023-10-01'); // 通过字符串
const dateWithParams = new Date(2023, 9, 1); // 年月日(月份从0开始)
日期格式化
转换为本地字符串:
now.toLocaleDateString(); // "2023/10/1"(根据地区格式)
now.toISOString(); // "2023-10-01T00:00:00.000Z"(ISO标准格式)
自定义格式化(需手动拼接):
const formatted = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
日期计算
增减天数:
const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 增加1天
计算日期差(毫秒转天数):
const diffDays = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));
日期比较
直接比较时间戳:
if (date1.getTime() > date2.getTime()) {
console.log("date1更晚");
}
第三方库推荐
对于复杂操作(如时区处理),推荐使用库:

- Moment.js(已停止更新,但广泛使用):
moment().format('YYYY-MM-DD'); - date-fns(模块化轻量替代):
import { format } from 'date-fns'; format(new Date(), 'yyyy-MM-dd');
注意事项
- 月份从
0开始(0=一月,11=十二月)。 - 时区问题:
new Date(string)在不同浏览器中可能解析不同,建议使用YYYY-MM-DD格式。






