Comparing javascript date time and timestamp from PostgreSQL

10,887

var ds='2013-03-15 08:50:00';

without any timezone information you can't really tell what day it is. Assuming your string is in UTC, you can use the Date constructor if you replace the space with a 'T' and add a 'Z' at the end:

var ds='2013-03-15 08:50:00';

var day=new Date(ds.replace(' ','T')+'Z');

day.toUTCString()

Fri, 15 Mar 2013 08:50:00 GMT

You can write a Date parsing function that will parse ISO or sql formats,

which may be needed on some older browsers.

Date.fromISO= function(s){
    var day, tz,
    rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
    p= rx.exec(s) || [];
    if(p[1]){
        day= p[1].split(/\D/);
        for(var i= 0, L= day.length;i<L;i++){
            day[i]= parseInt(day[i], 10) || 0;
        };
        day[1]-= 1;
        day= new Date(Date.UTC.apply(Date, day));
        if(!day.getDate()) return NaN;
            //adjust for time zone offset:
        if(p[5]){
            tz= (parseInt(p[5], 10)*60);
            if(p[6]) tz+= parseInt(p[6], 10);
            if(p[4]== '+') tz*= -1;
            if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
        }
        return day;
    }
    return NaN;
}

then call Date.fromISO('2013-03-15 08:50:00');

Share:
10,887
user984621
Author by

user984621

Updated on June 23, 2022

Comments

  • user984621
    user984621 almost 2 years

    In PostgreSQL database, I have save in the timestamp column this value: 2013-03-15 08:50:00. My goal is to take this date from database and check, if the current time is less about 12 hours than the time from database.

    For this purpose, I wanted to get the current time from new Date() and compare it with the date from database - but this doesn't work because of different time formats.

    How could I do that and convert those times on the same (comparable) format?