javascript date对象常用方法有哪些?
推荐
在线提问>>
JavaScript 中的 `Date` 对象是用于处理日期和时间的内置对象,提供了一系列方法用于获取、设置和操作日期和时间。下面是 `Date` 对象常用的方法:
1. `getDate()`:获取日期中的天数(1-31)。
2. `getMonth()`:获取日期中的月份(0-11)。
3. `getFullYear()`:获取日期中的年份(四位数)。
4. `getHours()`:获取时间中的小时数(0-23)。
5. `getMinutes()`:获取时间中的分钟数(0-59)。
6. `getSeconds()`:获取时间中的秒数(0-59)。
7. `getMilliseconds()`:获取时间中的毫秒数(0-999)。
8. `getTime()`:获取时间戳,即从 1970 年 1 月 1 日开始计算的毫秒数。
9. `getDay()`:获取日期中的星期几(0-6),其中 0 表示星期日。
10. `toISOString()`:将日期对象转换为 ISO 8601 格式的字符串。
11. `toUTCString()`:将日期对象转换为 UTC 时间的字符串表示。
12. `toString()`:将日期对象转换为字符串表示,包含日期和时间信息。
13. `setDate()`:设置日期中的天数。
14. `setMonth()`:设置日期中的月份。
15. `setFullYear()`:设置日期中的年份。
16. `setHours()`:设置时间中的小时数。
17. `setMinutes()`:设置时间中的分钟数。
18. `setSeconds()`:设置时间中的秒数。
19. `setMilliseconds()`:设置时间中的毫秒数。
20. `now()`:获取当前时间的时间戳。
除了上述方法,`Date` 对象还提供了其他一些方法,如日期比较、日期格式化等,可以根据具体需求进行使用。
示例代码如下:
const currentDate = new Date();
console.log(currentDate.getDate()); // 获取当前日期的天数
console.log(currentDate.getMonth()); // 获取当前日期的月份
console.log(currentDate.getFullYear()); // 获取当前日期的年份
console.log(currentDate.getHours()); // 获取当前时间的小时数
console.log(currentDate.getMinutes()); // 获取当前时间的分钟数
console.log(currentDate.getSeconds()); // 获取当前时间的秒数
console.log(currentDate.getMilliseconds()); // 获取当前时间的毫秒数
console.log(currentDate.getTime()); // 获取当前时间的时间戳
console.log(currentDate.getDay()); // 获取当前日期的星期几
currentDate.setFullYear(2022); // 设置日期的年份
currentDate.setHours(10); // 设置时间的小时数
console.log(currentDate.toISOString()); // 转换为 ISO 8601 格式的字符串
console.log(currentDate.toString()); // 转换为字符串表示
通过 `Date` 对象提供的方法,可以对日期和时间进行灵活的操作和处理,满足各种需求。