在 docker 中设置 node.js 时区

CI 使用 Docker 打包前端代码,流程中有使用 Shell 和 Node.js 两种方式输出时间。
Shell 脚本用 $(date ‘+%F %T’) 输出的是东 8 区字符串 2021-05-27 14:43:23
Node.js 用 new Date().toString() 输出的是 0 时区字符串 Thu May 27 2021 06:43:09 GMT+0000 (Coordinated Universal Time)

经验证,虽然已将宿主机 /etc/localtime 挂载至 Docker 同路径,但仍需要配置环境变量 TZ=Asia/Shanghai 才可生效。
似乎是 V8 引擎在浏览器环境与服务器环境的实现方案不一致造成的。该 TZ 参数暂时不支持 Windows 但很快就会支持。

另外,顺便发现 new Date() 在解析不带时区的时间字符串时,ES5 和 ES6 有不同的规范。

参考资料:
https://github.com/nodejs/node/issues/19480
https://github.com/nodejs/node/issues/28743
https://github.com/nodejs/node/issues/4230
https://github.com/nodejs/docker-node/issues/626
https://github.com/gliderlabs/docker-alpine/issues/136
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
https://docs.microsoft.com/en-us/cpp/c-runtime-library/time-management?view=msvc-160
https://github.com/nodejs/node/blob/4ebb88fea5a9d83f2c4ec566e958d735f1fca138/deps/v8/src/base/platform/platform-win32.cc#L131

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注