Date.UTC Builds Timestamps Without Timezone Drift
Build timestamps with Date.UTC so month math and comparisons stay independent of the machine time zone, then format and parse them.
Code
// Date.UTC:按 UTC 字段构造时间戳,不受本机时区影响
const stamp = Date.UTC(2026, 10, 17, 9, 30);
const local = new Date(stamp);
console.log('epoch ms:', stamp);
console.log('iso:', local.toISOString());
console.log('parsed equal:', Date.parse('2026-11-17T09:30:00Z') === stamp);
// 月份从 0 开始;UTC 与本地字段可能不同
console.log('utc month:', local.getUTCMonth(), '| local month:', local.getMonth());
console.log('utc hours:', local.getUTCHours());
// 用固定偏移做比较,避免夏令时影响
const offsets = [0, 60, -60].map((minutes) => {
const shifted = new Date(stamp + minutes * 60_000);
return shifted.getUTCHours();
});
console.log('utc hours after shifts:', offsets.join(','));
// 日期运算跨越月份边界时仍然精确
const nextMonth = Date.UTC(2026, 11, 1) - stamp;
console.log('ms until december:', nextMonth);Output
Captured from a sandboxed run of this snippet in the build pipeline.
epoch ms: 1794907800000
iso: 2026-11-17T09:30:00.000Z
parsed equal: true
utc month: 10 | local month: 10
utc hours: 9
utc hours after shifts: 9,10,8
ms until december: 1175400000How it works
Top-level bindings stamp, local, offsets, nextMonth hold the demo state — nothing sits inside a function scope.
Applying it
The run emits 7 labeled sections — epoch ms:, iso:, parsed equal:, utc month:, utc hours:, utc hours after shifts:, ms until december: — one per step.
Statements that matter
const offsets = [0, 60, -60].map((minutes) => {
const shifted = new Date(stamp + minutes * 60_000);
return shifted.getUTCHours();
});
Interactive Tools for This Topic
Timezone Offset FinderLook up the UTC offset, abbreviation, and local time for any IANA time zone at a given instant, and see whether the zone observes daylight saving.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `stamp`, `local`, `offsets`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.