1. 获取当前时间
const now = new Date(); // 当前时间对象
const timestamp = Date.now(); // 当前时间戳(毫秒)
2. 时间戳与日期对象转换
时间戳 → 日期对象
const timestamp = 1633948800000;
const dateObj = new Date(timestamp);
日期对象 → 时间戳
const dateObj = new Date();
const timestamp1 = dateObj.getTime();
const timestamp2 = dateObj.valueOf();
const timestamp3 = Date.parse(dateObj); // 注意:Date.parse 返回的是数字
3. 日期字符串与日期对象转换
字符串 → 日期对象
const dateStr = '2023-10-10T08:00:00';
const dateObj1 = new Date(dateStr);
const dateObj2 = new Date('2023/10/10 08:00:00');
const dateObj3 = new Date('October 10, 2023 08:00:00');
日期对象 → 字符串
const dateObj = new Date();// 本地时间字符串
console.log(dateObj.toString()); // "Tue Oct 10 2023 16:00:00 GMT+0800 (中国标准时间)"
console.log(dateObj.toLocaleString()); // "2023/10/10 16:00:00"// ISO格式
console.log(dateObj.toISOString()); // "2023-10-10T08:00:00.000Z" (UTC时间)// 其他格式
console.log(dateObj.toDateString()); // "Tue Oct 10 2023"
console.log(dateObj.toTimeString()); // "16:00:00 GMT+0800 (中国标准时间)"
console.log(dateObj.toUTCString()); // "Tue, 10 Oct 2023 08:00:00 GMT"
4. 时间计算
加减时间
const dateObj = new Date();// 加1天
dateObj.setDate(dateObj.getDate() + 1);// 加2小时
dateObj.setHours(dateObj.getHours() + 2);// 加30分钟
dateObj.setMinutes(dateObj.getMinutes() + 30);// 使用时间戳计算
const oneDayLater = new Date(dateObj.getTime() + 24 * 60 * 60 * 1000);
计算时间差
const date1 = new Date('2023-10-10T08:00:00');
const date2 = new Date('2023-10-11T08:00:00');// 毫秒差
const diffMs = date2 - date1;// 转换为天、小时、分钟、秒
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffMinutes = Math.floor(diffMs / (1000 * 60));
const diffSeconds = Math.floor(diffMs / 1000);