js教程

javascript获取当前时间方法汇总

我的站长站 2023-09-28 人阅读

1. Date()方法

Date() 函数用于创建一个包含当前日期和时间的新 Date 对象。

const now = new Date();
console.log(now);

输出:

Wed Sep 15 2021 15:21:45 GMT+0800 (中国标准时间)

2. getTime()方法

getTime() 函数返回从 1970 年 1 月 1 日到现在的毫秒数。

const now = new Date();
const timestamp = now.getTime();
console.log(timestamp);

输出:

1631692896415

3. getFullYear()方法

getFullYear() 函数返回当前年份。

const now = new Date();
const year = now.getFullYear();
console.log(year);

输出:

2021

4. getDate()方法

getDate() 函数返回当前月份的日数。

const now = new Date();
const day = now.getDate();
console.log(day);

输出:15

5. getMonth()方法

getMonth() 函数返回当前月份的数字(0-11)。

const now = new Date();
const month = now.getMonth();
console.log(month);

输出:

8

6. getDay()方法

getDay() 函数返回当前星期的数字(0-6)。

const now = new Date();
const weekday = now.getDay();
console.log(weekday);

输出:

3

7. getHours()方法

getHours() 函数返回当前时间的小时数。

const now = new Date();
const hours = now.getHours();
console.log(hours);

输出:15

8. getMinutes()方法

getMinutes() 函数返回当前时间的分钟数。

const now = new Date();
const minutes = now.getMinutes();
console.log(minutes);

输出:31

9. getSeconds()方法

getSeconds() 函数返回当前时间的秒数。

const now = new Date();
const seconds = now.getSeconds();
console.log(seconds);

输出:13

10. getMilliseconds()方法

getMilliseconds() 函数返回当前时间的毫秒数。

const now = new Date();
const milliseconds = now.getMilliseconds();
console.log(milliseconds);

输出:

974
JS教程标签