Skip to content

Instantly share code, notes, and snippets.

@cbumgard
Created December 11, 2012 01:03
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cbumgard/4254862 to your computer and use it in GitHub Desktop.
Save cbumgard/4254862 to your computer and use it in GitHub Desktop.
Formatting dates/times in node.js using Olson timezones and moment.js. Converts server-side timestamps to the browser's timezone.
var moment = require('moment');
var tz = require('timezone/loaded');
var time = require('time');
module.exports = function() {
var strftime_format = '%F %T %z'; // used to convert a date into a normalized strftime format with timezone
var moment_format = 'YYYY-MM-DD HH:mm:ss zz'; // moment.js LDML format for parsing date strings
/**
* Convert a Javascript Date into node-time wrapper with the appropriate timezone.
* @param date {Date} Javascript Date object
* @param timezone {String} Olson timezone for this date (e.g. 'America/New_York')
* @return node-time object with the appropriate timezone
*/
var to_local = function(date, timezone) {
var tz_date = new time.Date(date);
tz_date.setTimezone(timezone); // localize the date into the specified timezone
return local_datetime = tz(tz_date, strftime_format, timezone); // localized format w timezone offset
}
/**
* Convert a Javascript Date into a Moment.js moment obj with the appropriate timezone.
* Using the returned moment, you can call for example 'moment.calendar()' to get a
* human readable relative time such as 'last Friday at 3:52 PM'.
* @param date {Date} Javascript Date object
* @param timezone {String} Olson timezone for this date (e.g. 'America/New_York')
* @return moment with the appropriate timezone
*/
var to_moment = function(date, timezone) {
var local_datetime = to_local(date, timezone);
return moment(local_datetime, moment_format);
}
return {
to_local: to_local,
to_moment: to_moment
}
}

How To Use

Read the user's timezone (Olson format) from their web browser using jstz (https://bitbucket.org/pellepim/jstimezonedetect), and set it on a hidden login form input:

$('input#timezone').val( jstz.determine().name() );

Pass the timezone to node.js in aforementioned hidden form input on the login form.

<input type="hidden" name="timezone" id="timezone">

Store the timezone in the user's express session in their login POST route:

req.session.timezone = req.body.timezone;

Then format a stored Date to the user's timezone with moment.js's nice human readable relative calendar function (based on the date-util file in this gist):

date_util.to_moment(date, timezone).calendar();

The output looks like: 'last Friday at 3:52 PM' if this happened last Friday at 3:52 PM PST. Someone in New York would see 'last Friday at 6:52 PM'.

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