40 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2025-12-10 12:02:17 +08:00
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toZonedTime = void 0;
const index_js_1 = require("../_lib/tzParseTimezone/index.js");
const index_js_2 = require("../toDate/index.js");
/**
* @name toZonedTime
* @category Time Zone Helpers
* @summary Get a date/time representing local time in a given time zone from the UTC date
*
* @description
* Returns a date instance with values representing the local time in the time zone
* specified of the UTC time from the date provided. In other words, when the new date
* is formatted it will show the equivalent hours in the target time zone regardless
* of the current system time zone.
*
* @param date the date with the relevant UTC time
* @param timeZone the time zone to get local time for, can be an offset or IANA time zone
* @param options the object with options. See [Options]{@link https://date-fns.org/docs/Options}
* @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
*
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // In June 10am UTC is 6am in New York (-04:00)
* const result = toZonedTime('2014-06-25T10:00:00.000Z', 'America/New_York')
* //=> Jun 25 2014 06:00:00
*/
function toZonedTime(date, timeZone, options) {
date = (0, index_js_2.toDate)(date, options);
const offsetMilliseconds = (0, index_js_1.tzParseTimezone)(timeZone, date, true);
const d = new Date(date.getTime() - offsetMilliseconds);
const resultDate = new Date(0);
resultDate.setFullYear(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
resultDate.setHours(d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
return resultDate;
}
exports.toZonedTime = toZonedTime;