Skip to content

Instantly share code, notes, and snippets.

@osteenbergen
Created April 23, 2015 12:08
Show Gist options
  • Save osteenbergen/38259648aa81f6cf27b3 to your computer and use it in GitHub Desktop.
Save osteenbergen/38259648aa81f6cf27b3 to your computer and use it in GitHub Desktop.
Laterjs Timezone support with MomentJS Timezone library
// 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) ]
*/
@jfinkhaeuser
Copy link

Love it!

Don't love that later doesn't do this out of the box 😞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment