Published
Edited
Jan 29, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
dateInDestinationTimeZone = {
// Initialize the date as if it were in UTC time zone
const inputDate = new Date(dateString + 'Z');
const parts = ['year', 'month', 'day', 'hour', 'minute', 'second'];
// Convert it to the destination timezone, e.g. "Europe/Berlin"
const o = Object.assign(
...new Intl.DateTimeFormat('en-US',
{ ...Object.assign(...parts.map(p => ({ [p]: 'numeric' }))), hour12: false, timeZone }
)
.formatToParts(inputDate)
.map(part => ({ [part.type]: part.value }))
)
// Initialize a second date with the conversion result. This date's time will be shifted, but in reverse.
const shiftedDate = new Date(
Date.UTC(o.year, o.month - 1, o.day, o.hour, o.minute, o.second, inputDate.getMilliseconds())
);
return new Date(inputDate - new Date(shiftedDate - inputDate))
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
md`## As one line`
Insert cell
oneLineResult = { const i=new Date(dateString+'Z');const p=['year','month','day','hour','minute','second'];const o=Object.assign(...new Intl.DateTimeFormat('en-US',{ ...Object.assign(...p.map(p=>({[p]:'numeric'}))),hour12:false,timeZone}).formatToParts(i).map(p=>({ [p.type]:p.value})));const s=new Date(Date.UTC(o.year,o.month-1,o.day,o.hour,o.minute,o.second,i.getMilliseconds()));return new Date(i-new Date(s-i)) }
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more