So, I live in Philippines (GMT+8) my current time is June 1, 2020, 3:20 PM
The current UTC time is June 1 2020, 7:20 AM
.
I want it so I can manipulate the date using Pacific/Honolulu
(GMT-10) and the current time there is 31 May 2020, 9:20 PM
like:
const date = new Date();
date.setDate(l.getDate() + 1)
console.log(date)
// ...further manipulation of date
date.getTime() //unix timestamp
this will show the local timezone which is GMT+8.
So I want to choose a timezone, manipulate the date, then get the UTC timestamp of that manipulated date.
I tried various method like converting it first to UTC, but no luck - still can't seem to find any workaround to this.
I'm using timezone-support and date-fns (if this helps) in my project (sorry I can't use moment js) as the project is already quite big and is using date-fns for a long time.
So I ended up doing this since was using timezone-support:
first I imported and initialized the data:
import {
populateTimeZones,
listTimeZones,
getZonedTime,
findTimeZone,
getUnixTime,
setTimeZone,
convertTimeToDate,
} from 'timezone-support/dist/lookup-convert';
import timezoneData from 'timezone-support/dist/data-2012-2022';
// get the timezone support ready
populateTimeZones(timezoneData);
Then I created this helper function:
const dateConvertToTimezone = (fromTimeZone, toTimeZone, date = new Date()) => {
const tz = findTimeZone(fromTimeZone);
const time = {
hours: date.getHours(),
minutes: date.getMinutes(),
day: date.getDate(),
month: date.getMonth() + 1,
year: date.getFullYear(),
};
// set the timezone to get the time object for the selected timezone
const selectedTime = setTimeZone(time, tz);
// convert the timezone to local one
const convertedToLocal = convertTimeToDate(selectedTime);
const utc = findTimeZone(toTimeZone);
const convertedTime = getZonedTime(convertedToLocal, utc);
return convertedTime;
};
Then I can do something like:
const selectedTime = dateConvertToTimezone(
'Etc/UTC',
'Pacific/Honolulu',
new Date('May 31 2020, 21:20')
);
This will return the UTC for Honolulu time and not my local time.