js日期实现
日期对象创建
使用 new Date() 创建当前时间的日期对象:
const now = new Date();
传入特定参数创建指定日期:
const specificDate = new Date(2023, 11, 31); // 年月日(月份0-11)
const dateString = new Date("2023-12-31T00:00:00");
日期获取方法
获取日期各部分信息:
const year = now.getFullYear(); // 2023
const month = now.getMonth(); // 0-11
const day = now.getDate(); // 1-31
const hours = now.getHours(); // 0-23
获取星期几(0-6,0表示周日):
const dayOfWeek = now.getDay();
日期设置方法
修改日期各部分:
now.setFullYear(2024);
now.setMonth(5); // 6月
now.setDate(15);
日期格式化
转换为本地字符串:
now.toLocaleDateString(); // "2023/12/31"
now.toLocaleTimeString(); // "14:30:00"
自定义格式化函数:
function formatDate(date) {
return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`;
}
日期计算
时间戳计算(毫秒数):
const timestamp = now.getTime();
const tomorrow = new Date(timestamp + 86400000);
使用 Date.UTC() 处理UTC时间:
const utcDate = new Date(Date.UTC(2023, 11, 31));
第三方库推荐
对于复杂日期操作建议使用库:

- Moment.js(已停止更新但广泛使用)
moment().format('YYYY-MM-DD'); - date-fns(模块化现代替代)
import { format } from 'date-fns'; format(new Date(), 'yyyy-MM-dd'); - Day.js(轻量替代)
dayjs().format('YYYY-MM-DD');






