Nodejs RangeError:指定的时区无效

mat*_*twg 5 javascript node.js typescript

我有测试示例:

console.log("test");

const t = new Date().toLocaleString("en-US", {
  timeZone: "+0000"
});

console.log(t);
Run Code Online (Sandbox Code Playgroud)

Google Chrome 122.0.6182.0(官方版本)开发版(64 位) Chrome浏览器

或者尝试: https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#try_it

在浏览器控制台中 - 好的,但在 Nodejs 中 - 错误

test

/home/jdoodle.js:3
const t = new Date().toLocaleString("en-US", {
                     ^

RangeError: Invalid time zone specified: +0000
    at Date.toLocaleString (<anonymous>)
    at Object.<anonymous> (/home/jdoodle.js:3:22)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:49

Node.js v21.2.0
Run Code Online (Sandbox Code Playgroud)

示例: https: //www.jdoodle.com/ia/T3V

谁能向我解释为什么它不起作用以及如何使它起作用?

mat*_*twg 0

我倾向于Intl按区域名称使用,我需要所有区域的列表...这是一个包含国家和时区的示例,但可能还有其他...?

import * as ct from 'countries-and-timezones';

const TZ = Object.assign({}, ...Object.values(ct.getAllTimezones()).map((zone) => ({[zone.utcOffsetStr]: zone.name})));

/** 
{
  '+00:00': 'WET',
  '+01:00': 'MET',
  '+02:00': 'Europe/Vilnius',
  '+03:00': 'Europe/Volgograd',
  '-10:00': 'Pacific/Tahiti',
  '-09:00': 'Pacific/Gambier',
  '-03:00': 'Etc/GMT+3',
  '-04:00': 'Etc/GMT+4',
  '-06:00': 'Pacific/Galapagos',
  '-05:00': 'Etc/GMT+5',
  '-07:00': 'MST7MDT',
  '-08:00': 'Pacific/Pitcairn',
  '-02:00': 'Etc/GMT+2',
  '-01:00': 'Etc/GMT+1',
  '-03:30': 'America/St_Johns',
  '+11:00': 'Pacific/Noumea',
  '+07:00': 'Etc/GMT-7',
  '+10:00': 'Pacific/Port_Moresby',
  '+05:00': 'Indian/Maldives',
  '+06:00': 'Indian/Chagos',
  '+12:00': 'Pacific/Tarawa',
  '+04:00': 'Indian/Mauritius',
  '+09:00': 'Pacific/Palau',
  '+08:00': 'Etc/GMT-8',
  '+05:30': 'Asia/Kolkata',
  '+04:30': 'Asia/Kabul',
  '+05:45': 'Asia/Kathmandu',
  '+03:30': 'Asia/Tehran',
  '+06:30': 'Asia/Yangon',
  '+09:30': 'Australia/Darwin',
  '+08:45': 'Australia/Eucla',
  '+10:30': 'Australia/Lord_Howe',
  '-11:00': 'Pacific/Pago_Pago',
  '-12:00': 'Etc/GMT+12',
  '+13:00': 'Pacific/Tongatapu',
  '+14:00': 'Pacific/Kiritimati',
  '+12:45': 'Pacific/Chatham',
  '-09:30': 'Pacific/Marquesas'
}
*/

const t = new Intl.DateTimeFormat('en', {
                  year: 'numeric',
                  month: 'numeric',
                  day: 'numeric',
                  hour: 'numeric',
                  minute: 'numeric',
                  second: 'numeric',
                  timeZone: TZ['+00:00'],
              }).format(new Date());

console.log(t); // 1/9/2024, 2:49:57 PM
Run Code Online (Sandbox Code Playgroud)