Home » Javascript » convert (date and timestamp from postgresql) to javascript time

convert (date and timestamp from postgresql) to javascript time

Posted by: admin February 23, 2020 Leave a comment

Questions:

I have two columns in the PostgreSQL table(start_date(in date format) and cancellation_date(in timestamp format)). One is in date format and another is in timestamp format. I want to get the difference between two values in the number of days. I am sending the data in javascript.

How to calculate the difference in days in javascript? for example, one value is 2010-10-14. the second value is 2010-10-16 04:05:06. the difference will be 3 days.

My problem is that I get these two values in API response as PostgreSQL(date and timestamp) format. And a simple difference is not working(start_date-cancellation_date) in javascript.

How to&Answers:

You can convert the dates into new date objects and calculate the difference as follows:

        var date1 = new Date("2010-10-14");
        var date2 = new Date("2010-10-16 04:05:06");
        var timeDiff = Math.abs(date2.getTime() - date1.getTime());
        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
        console.log(diffDays);

Answer:

Javascript date objects can’t be compared until they’re converted to milliseconds.

var now = new Date(); // create new date - today
var then = new Date(now.getDate()+5); // create new date that's now + 5 days (bad variable name, sry)
var nowAdj = now.getTime(); // now adjusted to milliseconds
var thenAdj = then.getTime(); // then adjusted to milliseconds
var differenceInDays = Math.round((thenAdj - nowAdj)/(1000*60*60*24)) // Subtract now from then and multiply the results by the magic formula to return milliseconds to days.

Edit: Cleaned up a bit, “then” is still a terrible variable name 😉