0

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.

2 Answers 2

2

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

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

Comments

1

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

2 Comments

@sulil lama for some dates javascript console prints invalid date.
@code0079, when your date string is null, the new date will default to 1970, it will not work. You need to make sure that your dates are valid when saving to datebase and retrieving it from database..

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.