JavaScript Date:获取当前日期、时间和星期

用 new Date() 获取当前时刻,再调用 getFullYear()、getMonth() 和 getDate() 等方法读取各部分。这些方法使用运行环境的本地时区。显示月份时要给月份索引加一,获取星期则用 getDay()。

创建当前或固定日期

new Date() 创建一个表示调用时刻的对象。省略 new 时,Date() 返回表示当前时间的字符串。使用数字参数可以复现示例。下面的 7 表示八月,指定的时分秒按本地时区解释。getTime() 返回自 1970 年 1 月 1 日 00:00 UTC 起经过的毫秒数。要在不同环境中表示同一时刻,请使用包含 Z 或明确偏移量的标准日期时间字符串。 ECMAScript · Date Constructor

const now = new Date();
const sample = new Date(2024, 7, 19, 14, 5, 9, 42);

console.log(now.getTime());
console.log(sample.getMonth()); // 7

读取年、月、日和星期

getFullYear() 返回年份,getMonth() 返回 0 到 11 的月份索引,getDate() 返回 1 到 31 的日号。getDay() 返回星期编号,从星期日的 0 到星期六的 6。对 2024 年 8 月 19 日而言,后两个方法分别返回 19 和代表星期一的 1。 ECMAScript · Date.prototype.getDay()

const date = new Date(2024, 7, 19);

console.log(date.getFullYear());  // 2024
console.log(date.getMonth() + 1);  // 8
console.log(date.getDate());      // 19
console.log(date.getDay());       // 1

格式化时分秒和毫秒

getHours() 返回 0 到 23,getMinutes() 和 getSeconds() 返回 0 到 59。要把 5 显示为 05,请先将其转成字符串,再用 padStart(2, '0') 补零。getMilliseconds() 返回 0 到 999,把它补成三位就能将 42 显示为 042。

const date = new Date(2024, 7, 19, 14, 5, 9, 42);
const pad = (value, length = 2) => String(value).padStart(length, '0');
const hms = [date.getHours(), date.getMinutes(), date.getSeconds()];
const clock = hms.map(value => pad(value)).join(':');

console.log(clock + '.' + pad(date.getMilliseconds(), 3)); // 14:05:09.042

运行完整示例

将下面的代码保存为 date-example.html,然后用浏览器打开。页面会显示 2024-08-19、星期一和 14:05:09.042。星期编号用作数组索引,取出对应名称。时间戳随运行环境的时区而变。要查看当前值,把脚本首行的 new Date(2024, 7, 19, 14, 5, 9, 42) 换成 new Date(),然后刷新页面。每次加载只计算一次。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>查看 Date 对象</title>
</head>
<body>
<h1>查看 Date 对象</h1>
<dl>
  <dt>日期</dt>
  <dd><output id="calendar"></output></dd>
  <dt>星期</dt>
  <dd><output id="weekday"></output></dd>
  <dt>时间</dt>
  <dd><output id="clock"></output></dd>
  <dt>时间戳</dt>
  <dd><output id="timestamp"></output></dd>
</dl>
<script>
const date = new Date(2024, 7, 19, 14, 5, 9, 42);
const pad = (value, length = 2) => String(value).padStart(length, '0');
const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
const calendar = [date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate())].join('-');
const hms = [date.getHours(), date.getMinutes(), date.getSeconds()];
const clock = hms.map(value => pad(value)).join(':') + '.' + pad(date.getMilliseconds(), 3);

document.querySelector('#calendar').textContent = calendar;
document.querySelector('#weekday').textContent = weekdays[date.getDay()];
document.querySelector('#clock').textContent = clock;
document.querySelector('#timestamp').textContent = String(date.getTime());
</script>
</body>
</html>

区分本地日期与 UTC 日期

toISOString() 使用 UTC 表示时刻。直接截取字符串中的日期得到的是 UTC 日期,在午夜附近可能与本地日期不同。本地日期使用前面介绍的方法,UTC 日期各部分则可用 getUTCFullYear() 等方法读取。要按首尔等指定时区显示,给 Intl.DateTimeFormat 传入 timeZone。下面的示例是同一个时刻,按 UTC 是 8 月 19 日,按首尔时间已经是 8 月 20 日。 ECMAScript Internationalization API · DateTimeFormat

const instant = new Date('2024-08-19T23:30:00Z');
const seoul = new Intl.DateTimeFormat('en-GB', {
  timeZone: 'Asia/Seoul',
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
});

console.log(instant.toISOString().slice(0, 10)); // 2024-08-19
console.log(seoul.format(instant));             // 20/08/2024