8

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?

2
  • I like using date.js - datejs.com Commented Mar 13, 2013 at 21:18
  • 1
    Unless it's absolutely necessary to get the time from the client, why not get it from the server using whatever application code you are using to query the db? Commented Mar 13, 2013 at 21:44

1 Answer 1

6

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');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.