JavaScript 的 Date 对象用于处理日期和时间。它提供了丰富的方法和属性来创建、操作和格式化日期和时间。以下是对 JavaScript Date 对象的详细介绍:
创建 Date 对象
1、当前日期和时间
let now = new Date();
console.log(now); // 输出当前日期和时间2、指定日期和时间
使用字符串(不推荐,因为解析依赖于实现,可能因浏览器而异)
let specificDate = new Date("2023-10-01T12:00:00Z");
console.log(specificDate);使用时间戳(自1970年1月1日以来的毫秒数)
let timestampDate = new Date(1696176000000);
console.log(timestampDate);使用年、月、日等参数
let customDate = new Date(2023, 9, 1, 12, 0, 0); // 注意:月份从0开始,9代表10月
console.log(customDate);获取日期和时间组件
getFullYear():获取四位数的年份getMonth():获取月份(0-11)getDate():获取一个月中的某一天(1-31)getHours():获取小时(0-23)getMinutes():获取分钟(0-59)getSeconds():获取秒(0-59)getMilliseconds():获取毫秒(0-999)getDay():获取星期几(0代表星期日,1代表星期一,依此类推)getTimezoneOffset():返回当前时区与UTC的分钟差
let date = new Date();
console.log(date.getFullYear()); // 年
console.log(date.getMonth()); // 月
console.log(date.getDate()); // 日
console.log(date.getHours()); // 小时
console.log(date.getMinutes()); // 分钟
console.log(date.getSeconds()); // 秒
console.log(date.getMilliseconds()); // 毫秒
console.log(date.getDay()); // 星期几
console.log(date.getTimezoneOffset()); // 时区偏移设置日期和时间组件
setFullYear(year, [month], [day])setMonth(month, [day])setDate(day)setHours(hour, [min], [sec], [ms])setMinutes(min, [sec], [ms])setSeconds(sec, [ms])setMilliseconds(ms)setTime(milliseconds):设置自1970年1月1日以来的毫秒数
let date = new Date();
date.setFullYear(2025);
date.setMonth(1); // 2月(注意:月份从0开始)
date.setDate(15);
console.log(date);日期和时间格式化
toISOString():返回ISO格式的字符串(UTC时间)toUTCString():返回UTC时间的字符串表示toLocaleString():根据本地时间惯例返回字符串toLocaleDateString():根据本地时间惯例返回日期部分的字符串toLocaleTimeString():根据本地时间惯例返回时间部分的字符串toString():返回日期时间的字符串表示
let date = new Date();
console.log(date.toISOString());
console.log(date.toUTCString());
console.log(date.toLocaleString());
console.log(date.toLocaleDateString());
console.log(date.toLocaleTimeString());
console.log(date.toString());日期和时间计算
getTime():返回自1970年1月1日以来的毫秒数valueOf():与getTime()相同,返回自1970年1月1日以来的毫秒数
let date1 = new Date();
let date2 = new Date(date1.getTime() + 7 * 24 * 60 * 60 * 1000); // 7天后
console.log(date2);日期和时间比较
可以直接使用比较运算符(<, >, <=, >=, ==, !=)来比较两个 Date 对象,因为它们在内部表示为时间戳。
let date1 = new Date("2023-10-01");
let date2 = new Date("2023-10-10");
console.log(date1 < date2); // true注意事项
- 月份是从0开始的(0代表1月,11代表12月)。
- 星期几是从0开始的(0代表星期日,6代表星期六)。
- 时间和日期的解析可能因浏览器而异,因此最好使用明确的时间戳或参数来创建
Date对象。
通过掌握这些方法和属性,你可以有效地在JavaScript中处理日期和时间。
