js实现date
日期对象创建
使用 new Date() 创建当前日期对象:
const currentDate = new Date();
指定日期创建(年月日时分秒):
const specificDate = new Date(2023, 11, 31, 23, 59, 59); // 月份从0开始(11代表12月)
通过字符串解析日期:
const dateFromString = new Date("2023-12-31T23:59:59");
日期获取与设置
获取日期组件:

const year = currentDate.getFullYear(); // 年份
const month = currentDate.getMonth(); // 月份(0-11)
const day = currentDate.getDate(); // 当月第几天
const hours = currentDate.getHours(); // 小时
设置日期组件:
currentDate.setFullYear(2024);
currentDate.setMonth(0); // 设置为1月
日期格式化
转换为本地字符串:
const dateString = currentDate.toLocaleDateString(); // "2023/12/31"
const timeString = currentDate.toLocaleTimeString(); // "23:59:59"
自定义格式化(使用 Intl.DateTimeFormat):

const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short'
});
console.log(formatter.format(currentDate)); // "Dec 2023"
日期计算
时间差计算(毫秒):
const date1 = new Date(2023, 0, 1);
const date2 = new Date(2023, 11, 31);
const diffInMs = date2 - date1; // 差值毫秒数
const diffInDays = diffInMs / (1000 * 60 * 60 * 24); // 转换为天数
添加/减少时间:
currentDate.setDate(currentDate.getDate() + 7); // 增加7天
第三方库推荐
处理复杂日期操作可使用以下库:
- Moment.js(已停止维护,但广泛使用):
moment().add(1, 'weeks').format('YYYY-MM-DD'); - date-fns(轻量模块化):
import { addDays, format } from 'date-fns'; format(addDays(new Date(), 7), 'yyyy-MM-dd');
注意事项
- 月份范围是 0-11(0表示1月)。
- 时区问题需注意,
getHours()返回本地时区小时数。 - 跨浏览器解析日期字符串时建议使用
YYYY-MM-DD格式。






