Created
April 23, 2015 12:08
-
-
Save osteenbergen/38259648aa81f6cf27b3 to your computer and use it in GitHub Desktop.
Laterjs Timezone support with MomentJS Timezone library
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
// Timezone library | |
var moment = require("moment-timezone"); | |
// Later | |
var later = require("later"); | |
// The schedule we would like to support: | |
var sched = later.parse.text("at 17:00"); | |
// In March CET switches to CEST (daylight saving) so this is a nice example | |
var timezone = "Europe/Amsterdam"; | |
var start_date = new Date("2015-03-24"); | |
// Timezone we would like to schedule | |
var zone = moment.tz.zone(timezone); | |
// Offset in minutes for today; Amsterdam = -120 | |
var offset = zone.offset(start_date); | |
// Current Date | |
var now = new moment(start_date); | |
// Subtract the offset so we have a 'virtual' UTC | |
now.subtract(offset, "minutes"); | |
// Calculate the list of occurences using the virtual time | |
var list = later.schedule(sched).next(10, now.toDate()); | |
// Translate the result back to actual UTC | |
var result = list.map(function(time){ | |
var t = new moment(time); | |
// Undo the offset | |
t.add(offset, "minutes"); | |
// Now the tricky bit to support changing timezones | |
var offset_time = zone.offset(time); | |
t.add(offset_time - offset, "minutes"); | |
// Return javascript date object | |
return t.toDate(); | |
}); | |
console.log(result); | |
/* | |
[ Tue Mar 24 2015 17:00:00 GMT+0100 (CET), | |
Wed Mar 25 2015 17:00:00 GMT+0100 (CET), | |
Thu Mar 26 2015 17:00:00 GMT+0100 (CET), | |
Fri Mar 27 2015 17:00:00 GMT+0100 (CET), | |
Sat Mar 28 2015 17:00:00 GMT+0100 (CET), | |
Sun Mar 29 2015 17:00:00 GMT+0200 (CEST), <-- offset has changed and its still running at 17:00 | |
Mon Mar 30 2015 17:00:00 GMT+0200 (CEST), | |
Tue Mar 31 2015 17:00:00 GMT+0200 (CEST), | |
Wed Apr 01 2015 17:00:00 GMT+0200 (CEST), | |
Thu Apr 02 2015 17:00:00 GMT+0200 (CEST) ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Love it!
Don't love that later doesn't do this out of the box 😞