From 99382d2d5e97879e002292d30a57f5ce490a0d9f Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Wed, 29 Jan 2014 14:35:39 -0800 Subject: [PATCH] allow string timezone offsets of the form [-+]HHMM, closes #33 --- Readme.md | 7 +++++++ strftime.js | 25 ++++++++++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/Readme.md b/Readme.md index e8a8083..ec6378d 100644 --- a/Readme.md +++ b/Readme.md @@ -53,6 +53,13 @@ Time zones can be passed in as an offset from GMT in minutes. console.log(strftimeTZ('%F %T', new Date(1307472705067), 120)) // => 2011-06-07 20:51:45 +Alternatively you can use the timezone format used by ISO 8601, `+HHMM` or `-HHMM`. + + var strftimeTZ = require('strftime').strftimeTZ + console.log(strftimeTZ('', new Date(1307472705067), '-0700')) // => June 07, 11 11:51:45 + console.log(strftimeTZ('%F %T', new Date(1307472705067), '+0200')) // => 2011-06-07 20:51:45 + + Supported Specifiers ==================== diff --git a/strftime.js b/strftime.js index 640e06b..b8f9659 100644 --- a/strftime.js +++ b/strftime.js @@ -46,11 +46,11 @@ // locale is optional namespace.strftimeTZ = strftime.strftimeTZ = strftimeTZ; function strftimeTZ(fmt, d, locale, timezone) { - if (typeof locale == 'number' && timezone == null) { + if ((typeof locale == 'number' || typeof locale == 'string') && timezone == null) { timezone = locale; locale = undefined; } - return _strftime(fmt, d, locale, { timezone: timezone }); + return _strftime(fmt, d, locale, { timezone: timezone, utc: true }); } namespace.strftimeUTC = strftime.strftimeUTC = strftimeUTC; @@ -88,12 +88,27 @@ // Hang on to this Unix timestamp because we might mess with it directly below. var timestamp = d.getTime(); - if (options.utc || typeof options.timezone == 'number') { + var tz = options.timezone; + var tzType = typeof tz; + + if (options.utc || tzType == 'number' || tzType == 'string') { d = dateToUTC(d); } - if (typeof options.timezone == 'number') { - d = new Date(d.getTime() + (options.timezone * 60000)); + if (tz) { + // ISO 8601 format timezone string, [-+]HHMM + // + // Convert to the number of minutes and it'll be applied to the date below. + if (tzType == 'string') { + var sign = tz[0] == '-' ? -1 : 1; + var hours = parseInt(tz.slice(1, 3), 10); + var mins = parseInt(tz.slice(3, 5), 10); + tz = sign * (60 * hours) + mins; + } + + if (tzType) { + d = new Date(d.getTime() + (tz * 60000)); + } } // Most of the specifiers supported by C's strftime, and some from Ruby.