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

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

Bun 的测试运行器支持通过 `setSystemTime` 函数以编程方式设置系统时间。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
import { test, expect, setSystemTime } from "bun:test";

test("party like it's 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);
});
```

***

`setSystemTime` 函数通常与 [生命周期钩子](/test/lifecycle) 一起使用，以配置具有确定性的“假时钟”的测试环境。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
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={"theme":{"light":"github-light","dark":"dracula"}}
import { test, expect, beforeAll, setSystemTime } from "bun:test";

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

***

完整的 Bun 测试运行器模拟文档请参见 [文档 > 测试运行器 > 日期和时间](/test/dates-times)。
