allow string timezone offsets of the form [-+]HHMM, closes #33

This commit is contained in:
Sami Samhuri 2014-01-29 14:35:39 -08:00
parent 61f6193e57
commit 99382d2d5e
2 changed files with 27 additions and 5 deletions

View file

@ -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 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 Supported Specifiers
==================== ====================

View file

@ -46,11 +46,11 @@
// locale is optional // locale is optional
namespace.strftimeTZ = strftime.strftimeTZ = strftimeTZ; namespace.strftimeTZ = strftime.strftimeTZ = strftimeTZ;
function strftimeTZ(fmt, d, locale, timezone) { function strftimeTZ(fmt, d, locale, timezone) {
if (typeof locale == 'number' && timezone == null) { if ((typeof locale == 'number' || typeof locale == 'string') && timezone == null) {
timezone = locale; timezone = locale;
locale = undefined; locale = undefined;
} }
return _strftime(fmt, d, locale, { timezone: timezone }); return _strftime(fmt, d, locale, { timezone: timezone, utc: true });
} }
namespace.strftimeUTC = strftime.strftimeUTC = strftimeUTC; namespace.strftimeUTC = strftime.strftimeUTC = strftimeUTC;
@ -88,12 +88,27 @@
// Hang on to this Unix timestamp because we might mess with it directly below. // Hang on to this Unix timestamp because we might mess with it directly below.
var timestamp = d.getTime(); 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); d = dateToUTC(d);
} }
if (typeof options.timezone == 'number') { if (tz) {
d = new Date(d.getTime() + (options.timezone * 60000)); // 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. // Most of the specifiers supported by C's strftime, and some from Ruby.