在 JavaScript 中,如果想要实现时间格式化,常用的有以下 2 种方式。
- 使用 Date 对象提供的格式化方法。
- 自定义日期时间格式化。
Date 对象提供的格式化方法
在 JavaScript 中,我们可以使用 Date 对象内置的几种格式化方法,来快速获取不同格式的日期时间字符串。
1. 本地化格式方法
在 JavaScript 中,Date 对象提供了名为 “toLocaleXxxx()” 的本地化格式方法。这些本地化格式方法,会根据当前运行环境的语言和地区设置,来自动生成最符合本地习惯的日期和时间字符串。
| 方法 | 说明 | 效果 |
|---|---|---|
| toLocaleDateString() | 返回本地化的 “日期” 部分 | "2025/10/6" |
| toLocaleTimeString() | 返回本地化的 “时间” 部分 | "21:40:30" 或 "下午9:40:30" |
| toLocaleString() | 返回本地化的 “完整日期和时间” | "2025/10/6 21:40:30" |
示例 1:使用本地化格式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
const d = new Date()
const result1 = d.toLocaleDateString();
const result2 = d.toLocaleTimeString();
const result3 = d.toLocaleString();
console.log(result1);
console.log(result2);
console.log(result3);
</script>
</body>
</html>运行结果如下。
2025/10/6
23:30:30
2025/10/6 23:30:302. 标准化格式方法
在 JavaScript 中,Date 对象还提供了名为 “toXxxx()” 的标准化格式方法。这些标准化格式方法,一般用于获取更标准的、不带本地时区信息的格式。
| 方法 | 说明 | 效果 |
|---|---|---|
| toDateString() | 返回 “日期” 部分 | "Mon Oct 06 2025" |
| toTimeString() | 返回 “时间” 部分 | "21:40:30 GMT+0800 (CST)" |
| toISOString() | 返回符合 ISO 8601 标准的格式 | "2025-10-06T13:40:30.000Z" |
示例 2:使用标准化格式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
const d = new Date()
const result1 = d.toDateString();
const result2 = d.toTimeString();
const result3 = d.toISOString();
console.log(result1);
console.log(result2);
console.log(result3);
</script>
</body>
</html>运行结果如下。
Mon Oct 06 2025
23:35:22 GMT+0800 (中国标准时间)
2025-10-06T15:35:22.587Z自定义日期时间格式
在实际开发中,我们经常需要将日期时间定义成 “YYYY/MM/DD hh:mm:ss” 或 “YYYY年MM月DD日” 这样的格式。此时就需要我们手动提取 Date 对象的年、月、日、时、分、秒等信息,然后来进行拼接了。
示例 3:自定义 “YYYY-MM-DD hh:mm:ss” 格式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
const now = new Date();
// 年、月、日
const year = now.getFullYear();
// 月份需要 +1,并添加前导 0
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const date = now.getDate().toString().padStart(2, '0');
// 时、分、秒
const hour = now.getHours().toString().padStart(2, '0');
const minute = now.getMinutes().toString().padStart(2, '0');
const second = now.getSeconds().toString().padStart(2, '0');
// 拼接成自定义格式
const result = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
console.log(result);
</script>
</body>
</html>运行结果如下。
2025-05-20 13:14:30分析:
在这个例子中,我们使用了 padStart() 方法用于确保当获取的数字是 “一位数字” 时,然后在前面加上一个 “0”。
