> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 在 Bun 的测试运行器中设置系统时间

使用 `bun:test` 中的 `setSystemTime` 函数在测试中设置系统时间。

```ts theme={null}
import { test, expect, setSystemTime } from "bun:test";

test("像 1999 年一样狂欢", () => {
  const date = new Date("1999-01-01T00:00:00.000Z");
  setSystemTime(date); // 现在时间是 1999 年 1 月 1 日

  const now = new Date();
  expect(now.getFullYear()).toBe(1999);
  expect(now.getMonth()).toBe(0);
  expect(now.getDate()).toBe(1);
});
```

***

在[生命周期钩子](/test/lifecycle)（如 `beforeAll`）中调用 `setSystemTime`，为你的测试提供确定性的"假时钟"。

```ts theme={null}
import { test, expect, beforeAll, setSystemTime } from "bun:test";

beforeAll(() => {
  const date = new Date("1999-01-01T00:00:00.000Z");
  setSystemTime(date); // 现在时间是 1999 年 1 月 1 日
});

// 测试...
```

***

要将系统时钟重置为实际时间，请不带参数调用 `setSystemTime`。

```ts theme={null}
import { test, expect, beforeAll, setSystemTime } from "bun:test";

setSystemTime(); // 重置为实际时间
```

***

参见 [日期和时间](/test/dates-times)。
