JavaScript 的 Date 对象表示日期和时间。可以使用 new Date() 构造函数创建一个 Date 对象,如果不传递任何参数,它会返回当前日期和时间。
例如:
javascriptCopy code
let now = new Date();
console.log(now);
你也可以传递字符串或整数作为参数来创建一个特定的日期,例如:
javascriptCopy code
let birthday = new Date("January 1, 1970");
console.log(birthday);
let timestamp = new Date(0);
console.log(timestamp);
要访问 Date 对象的属性,可以使用如下方法:
getFullYear():返回完整的年份(4 位数字)。getMonth():返回月份(0 到 11)。getDate():返回日期(1 到 31)。getHours():返回小时(0 到 23)。getMinutes():返回分钟(0 到 59)。getSeconds():返回秒(0 到 59)。
例如:
javascriptCopy code
let now = new Date();
console.log("Year: " + now.getFullYear());
console.log("Month: " + (now.getMonth() + 1));
console.log("Date: " + now.getDate());
console.log("Hours: " + now.getHours());
console.log("Minutes: " + now.getMinutes());
console.log("Seconds: " + now.getSeconds());
此外,还可以使用如下方法来格式化日期:
toDateString():返回简单的日期字符串,如 "Mon Feb 03 2023"。toTimeString():返回简单的时间字符串,如 "11:45:30 GMT+0800 (中国标准时间)"。toLocaleDateString()