Last active
September 22, 2015 22:20
-
-
Save swashcap/18fa5e6f7eed69d7c36a to your computer and use it in GitHub Desktop.
Postgres Standard Timestamp Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Parse Postgres's standard timestamps. | |
* | |
* Example: `Tue Jan 01 2019 00:00:00 GMT+0000 (UTC)` | |
* | |
* @todo Write tests! | |
*/ | |
var MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', | |
'august', 'september', 'october', 'november', 'december']; | |
/** | |
* Pad a number with zeros. | |
* | |
* @param {number} number | |
* @param {string} pad Output length | |
* @return {string} Zero-padded number | |
*/ | |
function zeroPad(number, pad) { | |
pad = pad || 2; | |
var target = number.toString(); | |
while(target.length < pad) { | |
target = '0' + target; | |
} | |
return target; | |
} | |
/** | |
* Get the month's number ('Jan' is 1, 'Feb' is 2...). | |
* | |
* @param {string} month Postgres-style month | |
* @return {number} Base-1 month number | |
*/ | |
function getMonth(month) { | |
var offset = 0; | |
for (var i = 0, il = MONTHS.length; i < il; i++) { | |
if (MONTHS[0].indexOf(month) !== 0) { | |
offset = i; | |
break; | |
} | |
} | |
return ++offset; | |
} | |
/** | |
* Get the timezone. | |
* | |
* @todo Implement this! | |
* | |
* @param {string} abbr | |
* @param {number} offset | |
* @param {string} code | |
* @return {string} | |
*/ | |
function getTimezone(abbr, offset, code) { | |
return 'Z'; | |
} | |
/** | |
* Get an ISO 8601-formatted date-time. | |
* | |
* @param {object} tokens | |
* @return {string} | |
*/ | |
function getISO8601DateTime(tokens) { | |
return ( | |
tokens.year + '-' + | |
tokens.month + '-' + | |
tokens.day + 'T' + | |
tokens.hour + ':' + | |
tokens.minute + ':' + | |
tokens.second + | |
tokens.timezone | |
); | |
} | |
module.exports = function parsePostgresStandardTimestamp(timestamp) { | |
var tokens = timestamp.split(/[ :\+]/); | |
return getISO8601DateTime({ | |
month: zeroPad(getMonth(tokens[1])), | |
day: zeroPad(parseInt(tokens[2], 10)), | |
year: parseInt(tokens[3], 10), | |
hour: zeroPad(parseInt(tokens[4], 10)), | |
minute: zeroPad(parseInt(tokens[5], 10)), | |
second: zeroPad(parseInt(tokens[6], 10)), | |
timezone: getTimezone(tokens[7], parseInt(tokens[8], 10), tokens[9]), | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment