js实现日期
日期对象创建与基本操作
使用 new Date() 创建日期对象,支持多种参数格式:
const now = new Date(); // 当前时间
const specificDate = new Date('2023-10-01'); // 字符串格式
const timestampDate = new Date(1696137600000); // 时间戳
const partsDate = new Date(2023, 9, 1); // 年, 月(0-11), 日
日期格式化
通过内置方法或自定义函数格式化日期:

const date = new Date();
console.log(date.toISOString()); // "2023-10-01T12:00:00.000Z"
console.log(date.toLocaleDateString('zh-CN')); // "2023/10/1"
// 自定义格式化
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}`;
}
日期计算
使用 set 和 get 方法进行日期加减:

const date = new Date();
date.setDate(date.getDate() + 7); // 加7天
date.setMonth(date.getMonth() - 1); // 减1个月
// 计算日期差(毫秒)
const date1 = new Date('2023-10-01');
const date2 = new Date('2023-10-10');
const diffDays = Math.floor((date2 - date1) / (1000 * 60 * 60 * 24)); // 9
第三方库推荐
对于复杂需求,可使用以下库简化操作:
- Moment.js(已停止维护,但广泛使用):
moment().format('YYYY-MM-DD'); - date-fns(现代轻量替代):
import { format, addDays } from 'date-fns'; format(new Date(), 'yyyy-MM-dd'); addDays(new Date(), 7);
时区处理
使用 toLocaleString 或库处理时区:
new Date().toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
注意事项
- 月份从
0(1月)到11(12月)。 - 时间戳单位为毫秒,UNIX 时间戳需乘以
1000。 - 跨浏览器解析日期字符串时建议使用
YYYY-MM-DD格式。






