Home » Javascript » Generate server-side Timestamp with Timezone for Postgresql tswtz data-type

Generate server-side Timestamp with Timezone for Postgresql tswtz data-type

Posted by: admin October 29, 2018 Leave a comment

Questions:

I currently fiddle around with generating a timestamp with timezone according to the datatype-definition of TSWTZ of PostGreSQL9.6 in javascript in my PEAN project (Postgres, Express, Angular & Node).

The definition according to the doc is: TIMESTAMP WITH TIME ZONE ‘2004-10-19 10:23:54+02’

I created this code-snippet here and it’s working, but i’m sure it can be improved without lacking in readability via reg-ex/pattern matching or other approaches.

/* double digits for Date */
Date.prototype.yyyymmdd = function() {
    var mm = (this.getMonth() + 1).toString(); // getMonth() based on 0
    var dd = this.getDate().toString();
    return [this.getFullYear(), mm.length===2 ? '' : '0', mm, dd.length===2 ? '' : '0', dd].join(''); // padding
};

/* double digits for time */
function checkTime(i) {
    return (i < 10) ? "0" + i : i;
}

function getTSWTZ() {
    /* get padded date */
    var today = new Date();
    var todayString = today.yyyymmdd();
    var yyyy = todayString.slice(0,4);
    var mm = todayString.slice(4,6);
    var dd = todayString.slice(6,8);
    var paddedDateString = yyyy + '-' + mm + '-' + dd + ' ';
    /* get padded time */
    h = checkTime(today.getHours());
    m = checkTime(today.getMinutes());
    s = checkTime(today.getSeconds());
    paddedTimeString = h + ":" + m + ":" + s;
    /* get offset of timezone */
    var tzStr = new Date().toString();
    var pos1 = tzStr.indexOf("GMT") +3;
    var pos2 = pos1 + 3;
    var offSetTimeZone = tzStr.slice(pos1, pos2);
    var tswtz = paddedDateString + paddedTimeString + offSetTimeZone;
    return tswtz;
};

What are your ideas on this one?

Answers: