js中提供了一个Date对象供我们获取当前时间。
基本语法:
new Date();
// 依据系统设置的当前时间来创建一个 Date 对象
通过new
来创建一个Date
的实例对象,如果直接调用Date(),则会返回一个字符串表示当前时间。
一些Date有关的API:
Date.now()
返回自 1970-1-1 00:00:00 UTC(世界标准时间)至今所经过的毫秒数。
Date.prototype.getDay()
根据本地时间,返回一个指定的 Date 对象是在一周中的第几天(0-6),0 表示星期天。
Date.prototype.getFullYear()
根据本地时间,返回一个指定的 Date 对象的完整年份(四位数年份)。
new Date().getFullYear();
// 2022
Date.prototype.getMonth()
根据本地时间,返回一个指定的 Date 对象的月份(0–11),0 表示一年中的第一月。
Date.prototype.getDate()
根据本地时间,返回一个指定的 Date 对象为一个月中的哪一日(1-31)。
Date.prototype.getHours()
根据本地时间,返回一个指定的 Date 对象的小时(0–23)。
Date.prototype.getMinutes()
根据本地时间,返回一个指定的 Date 对象的分钟数(0–59)。
Date.prototype.getSeconds()
根据本地时间,返回一个指定的 Date 对象的秒数(0–59)。
Date.prototype.getMilliseconds()
根据本地时间,返回一个指定的 Date 对象的毫秒数(0–999)。
Date.prototype.getTime()
返回一个数值,表示从 1970 年 1 月 1 日 0 时 0 分 0 秒 距离该 Date 对象所代表的时间经过的毫秒数。
下面是获取当前时间的方法:
function getNowTime() {
const nowDate = new Date();
const [year, month, day, hour, minute, second] =
[
nowDate.getFullYear(),
nowDate.getMonth() + 1,
nowDate.getDate(),
nowDate.getHours(),
nowDate.getMinutes(),
nowDate.getSeconds()
];
// getDay() 获取的是星期
return year + "年" + month + "月" +
day + "日" + hour + ":" + minute + ":" + second;
}