Last active
April 23, 2018 19:40
-
-
Save bradoyler/cf62916a7d3b19aa8df957e72303605e to your computer and use it in GitHub Desktop.
Converting a UTC datetime to EDT timezone using date-fns.js (without using an IANA db)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import parse from 'date-fns/parse'; | |
import format from 'date-fns/format'; | |
import isValid from 'date-fns/is_valid'; | |
import addMinutes from 'date-fns/add_minutes'; | |
export default function (datetime) { | |
const parsed = parse(datetime); | |
if (!isValid(parsed)) { // return empty & log error for invalid dates | |
console.error('invalid date:', datetime); | |
return ''; | |
} | |
const utcOffset = parsed.getTimezoneOffset(); | |
const isDST = (utcOffset < new Date(2016, 1, 1).getTimezoneOffset()); | |
const edtOffset = isDST ? 240 : 300; // 300mins or 240mins during Daylight savings | |
const offsetDiff = utcOffset - edtOffset; | |
let adjustedTime = parsed; | |
if (offsetDiff) { | |
adjustedTime = addMinutes(parsed, offsetDiff); | |
} | |
return `${format(adjustedTime, 'MMM.DD.YYYY / h:mm A [ET]')}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment