Last active
October 2, 2020 16:29
-
-
Save acoyfellow/4a87d7f6fa0a117059a3ee787f05ad35 to your computer and use it in GitHub Desktop.
Turn a time into a time-zoned future timestamp (date-fns + date-fns-timezone)
This file contains 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
const { | |
convertToTimeZone | |
} = require('date-fns-timezone'); | |
const dateFns = require("date-fns"); | |
const { | |
format, | |
getTime, | |
startOfToday, | |
parse, | |
addDays, | |
} = dateFns; | |
// given a human legible string time + timezone, | |
// return the next available time in that timezone. | |
// no past timestamps allowed. | |
const getTzTimestamp = ( | |
time = '4:20 PM', | |
timeZone = 'America/New_York' | |
) => { | |
let now= convertToTimeZone( | |
new Date(), | |
{ timeZone } | |
); | |
let nowStamp= getTime(now); | |
let day = parse( | |
time, | |
'h:mm a', | |
now | |
); | |
let tzStamp= getTime(day); | |
if(now > day){ | |
day= addDays(day, 1); | |
}; | |
let timestamp = getTime(day); | |
let string= format(day, 'LLL do @ h:mm a') | |
return { day, timestamp, string }; | |
}; | |
const t= '11:48 PM'; | |
//const nd= getTzTimestamp(t, 'America/North_Dakota/Center'); | |
const la= getTzTimestamp(t, 'America/Los_Angeles'); | |
const ny= getTzTimestamp(t, 'America/New_York'); | |
console.log({t}); | |
console.table({ ny, la }); | |
/* | |
{ t: '11:48 PM' } | |
┌─────────┬──────────────────────────┬───────────────┬──────────────────────┐ | |
│ (index) │ day │ timestamp │ string │ | |
├─────────┼──────────────────────────┼───────────────┼──────────────────────┤ | |
│ ny │ 2020-10-02T23:48:00.000Z │ 1601682480000 │ 'Oct 2nd @ 11:48 PM' │ | |
│ la │ 2020-10-02T23:48:00.000Z │ 1601682480000 │ 'Oct 2nd @ 11:48 PM' │ | |
└─────────┴──────────────────────────┴───────────────┴──────────────────────┘ | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment