在 JavaScript 中,你可以使用 Date
对象来获取 当前日期 和 当前时间,以下是具体方法和示例代码:
1. 获取当前日期
使用 Date
对象的方法获取 年、月、日,并可以格式化为常见的日期字符串。
方法:
const now = new Date(); // 创建 Date 对象,包含当前日期和时间
// 获取年、月、日(注意月份从 0 开始,需要 +1)
const year = now.getFullYear(); // 2025(四位年份)
const month = now.getMonth() + 1; // 6(实际是 6 月,但 getMonth() 返回 5)
const day = now.getDate(); // 9(当月的第几天)
// 格式化为 YYYY-MM-DD
const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
console.log(formattedDate); // 输出:2025-06-09
2. 获取当前时间
使用 Date
对象的方法获取 时、分、秒、毫秒,并可格式化为时间字符串。
方法:
const hours = now.getHours(); // 当前小时(0-23)
const minutes = now.getMinutes(); // 当前分钟(0-59)
const seconds = now.getSeconds(); // 当前秒(0-59)
// 格式化为 HH:MM:SS
const formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
console.log(formattedTime); // 例如:14:30:45(根据当前时间)
3. 同时获取日期和时间
可以直接用 toLocaleString()
或自定义格式组合:
示例:
// 方法1:使用 toLocaleString(依赖系统区域设置)
console.log(now.toLocaleString()); // 输出:2025/6/9 14:30:45(格式可能因系统而异)
// 方法2:自定义拼接
console.log(`当前时间:${formattedDate} ${formattedTime}`); // 输出:2025-06-09 14:30:45
4. 其他常用方法
-
now.toISOString()
→ 返回 ISO 格式的日期时间(UTC 时区),例如"2025-06-09T06:30:45.000Z"
。 -
now.toLocaleDateString()
→ 仅返回本地格式的日期(如"2025/6/9"
)。 -
now.toLocaleTimeString()
→ 仅返回本地格式的时间(如"14:30:45"
)。const now = new Date();
// 获取日期
const date =${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}
;// 获取时间
const time =${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}
;console.log(
当前日期:${date}
); // 2025-06-09
console.log(当前时间:${time}
); // 14:30:45
console.log(日期和时间:${date} ${time}
); // 2025-06-09 14:30:45
注意事项:
-
月份从 0 开始 :
getMonth()
返回0
(1月)到11
(12月),所以需要+1
。 -
补零操作 :用
padStart(2, '0')
确保个位数显示为01
、02
等。 -
时区问题 :以上方法均基于用户本地时区,如需 UTC 时间,可用
getUTC
系列方法(如getUTCHours()
)。