Merge pull request #943 from RivalIQ/utc-date-input

add option to parse input javascript Dates as UTC
This commit is contained in:
Brian C 2016-02-25 11:01:13 -06:00
commit 1c6da45d64
3 changed files with 41 additions and 9 deletions

View File

@ -40,8 +40,10 @@ var defaults = module.exports = {
ssl: false,
application_name : undefined,
fallback_application_name: undefined
application_name: undefined,
fallback_application_name: undefined,
parseInputDatesAsUTC: false
};
//parse int8 so you can get your count values as actual numbers

View File

@ -1,3 +1,4 @@
var defaults = require('./defaults');
// convert a JS array to a postgres array literal
// uses comma separator so won't work for types like box that use
@ -32,8 +33,12 @@ var prepareValue = function(val, seen) {
return val;
}
if(val instanceof Date) {
if(defaults.parseInputDatesAsUTC) {
return dateToStringUTC(val);
} else {
return dateToString(val);
}
}
if(Array.isArray(val)) {
return arrayString(val);
}
@ -59,13 +64,14 @@ function prepareObject(val, seen) {
return JSON.stringify(val);
}
function dateToString(date) {
function pad(number, digits) {
number = ""+number;
function pad(number, digits) {
number = "" +number;
while(number.length < digits)
number = "0"+number;
number = "0" + number;
return number;
}
}
function dateToString(date) {
var offset = -date.getTimezoneOffset();
var ret = pad(date.getFullYear(), 4) + '-' +
@ -86,6 +92,19 @@ function dateToString(date) {
return ret + pad(Math.floor(offset/60), 2) + ":" + pad(offset%60, 2);
}
function dateToStringUTC(date) {
var ret = pad(date.getUTCFullYear(), 4) + '-' +
pad(date.getUTCMonth() + 1, 2) + '-' +
pad(date.getUTCDate(), 2) + 'T' +
pad(date.getUTCHours(), 2) + ':' +
pad(date.getUTCMinutes(), 2) + ':' +
pad(date.getUTCSeconds(), 2) + '.' +
pad(date.getUTCMilliseconds(), 3);
return ret + "+00:00";
}
function normalizeQueryConfig (config, values, callback) {
//can take in strings or config objects
config = (typeof(config) == 'string') ? { text: config } : config;

View File

@ -65,6 +65,17 @@ test('prepareValues: date prepared properly', function() {
helper.resetTimezoneOffset();
});
test('prepareValues: date prepared properly as UTC', function() {
defaults.parseInputDatesAsUTC = true;
// make a date in the local timezone that represents a specific UTC point in time
var date = new Date(Date.UTC(2014, 1, 1, 11, 11, 1, 7));
var out = utils.prepareValue(date);
assert.strictEqual(out, "2014-02-01T11:11:01.007+00:00");
defaults.parseInputDatesAsUTC = false;
});
test('prepareValues: undefined prepared properly', function() {
var out = utils.prepareValue(void 0);
assert.strictEqual(out, null);