js 实现日期
在 JavaScript 中实现日期操作可以通过多种方式完成,以下是常见的方法和示例:
获取当前日期和时间
使用 Date 对象获取当前日期和时间:
const currentDate = new Date();
console.log(currentDate); // 输出当前日期和时间(如:Mon Jan 01 2024 12:00:00 GMT+0800)
创建指定日期
通过传递年、月、日等参数创建指定日期:
const specificDate = new Date(2024, 0, 1); // 月份从0开始(0表示1月)
console.log(specificDate); // 输出:Mon Jan 01 2024 00:00:00 GMT+0800
格式化日期
使用 toLocaleDateString 或自定义逻辑格式化日期:
const date = new Date();
const formattedDate = date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
console.log(formattedDate); // 输出:2024/01/01
计算日期差
通过时间戳计算日期差(单位:毫秒):
const date1 = new Date(2024, 0, 1);
const date2 = new Date(2024, 0, 10);
const diffInMs = date2 - date1; // 时间戳差值
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);
console.log(diffInDays); // 输出:9
日期加减
使用 setDate 或时间戳操作实现日期加减:
const date = new Date();
date.setDate(date.getDate() + 7); // 加7天
console.log(date.toLocaleDateString()); // 输出7天后的日期
第三方库推荐
对于复杂需求,可以使用第三方库如 moment.js 或 date-fns:
// 使用 date-fns 示例
import { format, addDays } from 'date-fns';
const today = new Date();
const nextWeek = addDays(today, 7);
console.log(format(nextWeek, 'yyyy-MM-dd')); // 输出:2024-01-08
注意事项
- 月份从
0开始(0表示 1 月)。 - 时区问题可能导致日期显示差异,建议使用 UTC 方法或明确时区处理。
- 浏览器兼容性需考虑,尤其是旧版本浏览器。







