Comparing javascript time and timestamp with PostgreSQL

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

For this purpose, I wanted to get the current time from new Date() and compare it with the date from the database, but this does not work due to different time formats.

How can I do this and convert these moments into the same (comparable) format?

+4
source share
1 answer

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

without any time zone information, you cannot say which day. Assuming your string is in UTC, you can use the Date constructor if you replace the space with “T” and add “Z” to the end:

 var ds='2013-03-15 08:50:00'; var day=new Date(ds.replace(' ','T')+'Z'); day.toUTCString() 

Fri, 15 March 2013 08:50:00 GMT

You can write a date parsing function that will process ISO or sql formats,

which may be required in 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') ;

+5
source

Source: https://habr.com/ru/post/1469075/


All Articles