> For the complete documentation index, see [llms.txt](https://chenzhihui.gitbook.io/note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chenzhihui.gitbook.io/note/misc/guo-ji-hua-shi-jian-chu-li.md).

# 国际化时间处理

最近遇到过这样一个场景，在一个国际化 项目中，利用时间戳范围筛数据的时候，发现总是筛不到正确的范围上。

通过观察发现，差了8小时。很直觉地发现了服务器存放的其实是UTC时间，在查看字段的时候，发现是用的 ISO9075 格式保存的数据，也就是像 `2020-01-01 11:24:33` 这样的格式，这就很难了，因为这是前端直接提交的字符串，也就是在保存的时候需要做一个格式化的 UTC 时间的字符串，而展示到网页上的时候，又需要格式化成当前时区的字符串。

翻阅 [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) 文档，发现可以使用一些 如 `date.getUTCFullYear()` 的方法来获取 UTC 的时间，但是考虑到我们的格式化工具一般是对当前时区进行的，为了尽可能的复用使用格式化工具，还是想采用当前时区的 Date 加上 与零时区的时差 来获得一个表示 零时区的 Date。

发现 `date.getTimezoneOffset` 这个方法可用。

```typescript

export function localDateToUtc(local: Date| string | number) {
  return addMinutes(new Date(local), new Date().getTimezoneOffset());
}

export function utcToLocalDate(utc: Date | string | number) {
  return addMinutes(new Date(utc), -new Date().getTimezoneOffset());
}
```
