js date实现
日期对象创建
使用 new Date() 构造函数创建日期对象,支持多种参数格式:
const now = new Date(); // 当前时间
const specificDate = new Date(2023, 11, 31); // 年月日(月份0-11)
const fromString = new Date("2023-12-31T12:00:00"); // ISO字符串
const fromTimestamp = new Date(1640995200000); // 时间戳(毫秒)
日期获取与设置
通过日期对象的方法获取或修改年、月、日等组成部分:

const date = new Date();
const year = date.getFullYear(); // 获取年份(4位数)
const month = date.getMonth(); // 获取月份(0-11)
date.setDate(15); // 设置日期为当月15号
date.setHours(23, 59, 59); // 设置时间为23:59:59
日期格式化
转换为字符串或自定义格式输出:
const date = new Date();
console.log(date.toISOString()); // "2023-12-31T12:00:00.000Z"
console.log(date.toLocaleDateString("zh-CN")); // "2023/12/31"(中文格式)
console.log(`${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`); // 自定义拼接
日期计算
通过时间戳或直接修改日期值进行计算:

const date1 = new Date("2023-12-01");
const date2 = new Date("2023-12-31");
const diffDays = (date2 - date1) / (1000 * 60 * 60 * 24); // 计算相差天数(30)
const nextWeek = new Date();
nextWeek.setDate(nextWeek.getDate() + 7); // 加7天
时区处理
处理时区差异或UTC时间:
const date = new Date();
const utcHours = date.getUTCHours(); // 获取UTC小时
date.setUTCFullYear(2024); // 设置UTC年份
console.log(date.toLocaleString("en-US", { timeZone: "America/New_York" })); // 纽约时区时间
日期库推荐
复杂操作建议使用第三方库:
- Moment.js(已停止更新,但广泛使用)
- date-fns(模块化轻量库)
- Day.js(Moment.js的轻量替代)
// Day.js示例
const dayjs = require('dayjs');
console.log(dayjs().format("YYYY-MM-DD HH:mm:ss"));






