js实现日期
日期对象创建
使用 new Date() 创建当前日期对象:
const now = new Date(); // 当前时间
指定日期创建对象:
const specificDate = new Date('2023-10-01'); // 字符串格式
const customDate = new Date(2023, 9, 1); // 月份从0开始(9表示10月)
日期格式化
转换为本地字符串:

console.log(now.toLocaleDateString()); // "2023/10/1"(格式因地区而异)
console.log(now.toLocaleTimeString()); // "14:30:00"
自定义格式化(手动拼接):
const formatted = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`;
日期计算
增减天数:

const tomorrow = new Date(now);
tomorrow.setDate(now.getDate() + 1); // 增加1天
计算日期差(毫秒数转天数):
const diffMs = new Date('2023-10-10') - now;
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
日期比较
直接比较时间戳:
const isLater = new Date('2023-10-10') > now; // true 或 false
第三方库推荐
对于复杂操作(如时区处理),推荐使用以下库:
- Moment.js(已停止更新,但广泛使用):
moment().format('YYYY-MM-DD'); - date-fns(模块化轻量替代):
import { format } from 'date-fns'; format(now, 'yyyy-MM-dd');
注意事项
- 月份从
0开始(0表示一月)。 - 时区问题需谨慎处理,建议使用
toISOString()或库函数统一时区。






