js实现日期
获取当前日期
使用 new Date() 可以获取当前日期和时间。返回的对象包含年、月、日、时、分、秒等信息。
const currentDate = new Date();
console.log(currentDate); // 输出当前日期和时间(如:Wed Jun 05 2024 14:30: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/06/05"(中文格式)
// 手动拼接
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
console.log(`${year}-${month}-${day}`); // 输出 "2024-06-05"
解析字符串为日期
使用 Date.parse() 或直接传入字符串到 new Date(),可以将符合格式的字符串转为日期对象。

const dateStr = '2024-06-05';
const parsedDate = new Date(dateStr);
console.log(parsedDate); // 输出对应的日期对象
// 注意:不同浏览器对字符串格式的兼容性可能不同
计算日期差
通过时间戳(毫秒数)计算两个日期的差值,再转换为天数、小时等单位。
const date1 = new Date('2024-06-05');
const date2 = new Date('2024-06-10');
const diffMs = date2 - date1; // 差值(毫秒)
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
console.log(diffDays); // 输出 5
日期加减操作
直接修改日期对象的组件(如 setDate),或使用库(如 date-fns)实现更复杂的操作。

const date = new Date('2024-06-05');
date.setDate(date.getDate() + 7); // 加7天
console.log(date.toLocaleDateString()); // 输出 "2024/6/12"
// 使用 date-fns(需安装)
import { addDays } from 'date-fns';
const newDate = addDays(date, 7);
console.log(newDate);
时区处理
使用 toLocaleString 指定时区,或通过 getTimezoneOffset() 获取本地时区偏移量。
const date = new Date();
console.log(date.toLocaleString('en-US', { timeZone: 'America/New_York' }));
const offset = date.getTimezoneOffset(); // 分钟数
console.log(`本地时区偏移:${offset} 分钟`);
第三方库推荐
对于复杂需求,推荐使用以下库:
- date-fns:轻量级、模块化。
- Day.js:类似 Moment.js 但更小巧。
- Luxon:支持时区和国际化。
// Day.js 示例
const dayjs = require('dayjs');
console.log(dayjs().format('YYYY-MM-DD'));






