-
Notifications
You must be signed in to change notification settings - Fork 112
/
index.js
48 lines (45 loc) · 1.99 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import tzParseTimezone from '../_lib/tzParseTimezone'
import subMilliseconds from 'date-fns/subMilliseconds'
import toDate from '../toDate'
/**
* @name utcToZonedTime
* @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|String|Number} date - the date with the relevant UTC time
* @param {String} timeZone - the time zone to get local time for, can be an offset or IANA time zone
* @param {OptionsWithTZ} [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}
* @returns {Date} the new date with the equivalent time in the time zone
* @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 = utcToZonedTime('2014-06-25T10:00:00.000Z', 'America/New_York')
* //=> Jun 25 2014 06:00:00
*/
export default function utcToZonedTime(dirtyDate, timeZone, options) {
var date = toDate(dirtyDate, options)
// This date has the UTC time values of the input date at the system time zone
var utcDate = new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds()
)
// We just need to apply the offset indicated by the time zone to this localized date
var offsetMilliseconds = tzParseTimezone(timeZone, date)
return offsetMilliseconds
? subMilliseconds(utcDate, offsetMilliseconds)
: utcDate
}