Skip to content

Instantly share code, notes, and snippets.

@tswaters
Last active April 6, 2017 20:42
Show Gist options
  • Save tswaters/b1725dfb7239edf555c28073a5959988 to your computer and use it in GitHub Desktop.
Save tswaters/b1725dfb7239edf555c28073a5959988 to your computer and use it in GitHub Desktop.
translating a provided date to a given timezone with moment-timezone
var moment = require('moment-timezone')
console.log(midnightPst('2017-12-31T13:59:59.999Z')) // provided as 11:59 HAST
console.log(midnightPst('2018-01-01T07:59:59.999Z')) // provided as 11:59 PST
console.log(midnightPst('2018-01-01T04:59:59.999Z')) // provided as 11:59 EST
console.log(midnightPst('2018-12-31T23:59:59.999Z')) // provided as 11:59 UTC
// east of GMT doesn't work.
console.log(midnightPst('2018-01-01T08:59:59.999Z')) // provided as 11:59 JST
function midnightPst (date) {
var dateUtc = moment(date)
// use moment.tz to translate this to PST
// from here, pull out the yyyy-mm-dd
// these will now be in PST, so instead of 8am jan.1 it is 12pm dec.31
// this breaks if the translation is AFTER gmt, it'll be a day out :(
var datePst = moment.tz(dateUtc, 'Canada/Pacific')
var year = datePst.year() // 2017
var month = datePst.month() // 12
var date = datePst.date() // 31
// generate moment array constructor - this bypasses current tz of system (utc)
// and will create a date timestamp for the provided format
return moment.tz([year, month, date], 'Canada/Pacific')
.endOf('day')
.format('YYYY-MM-DDTHH:mm:ss.SSSSZ')
}
// TZ=UTC node index.js
// 2017-12-31T23:59:59.9990-08:00
// 2017-12-31T23:59:59.9990-08:00
// 2017-12-31T23:59:59.9990-08:00
// 2018-12-31T23:59:59.9990-08:00
// 2018-01-01T23:59:59.9990-08:00 aww, so close.
//
// I hate dates.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment