Skip to content
Advertisement

How to compare two different date formats in javascript

Hi all I am new to date time things in javascript. I am facing one issue while comparing two different date formats. Objective- I want to compare date/time coming from the backend with the current time. If time coming from backend is past time I need to do some other stuff or if it is in future I want to do something else.

Issue- Current date format is something like this – Mon Jan 10 2022 16:38:58 GMT+0530 (India Standard Time) Date Time getting from backend is like – 2022-01-03T18:30:00Z

Code –

 $scope.getTimeDifference = function(meetingsData){
            meetingsData.forEach(function (arrayItem) {
                var currentTime  = new Date();
                var x = arrayItem.meetingTime;
                console.log(x);
                console.log(currentTime)

                if(x < currentTime){
                    console.log("meeting is in the past");
                }
                else{
                    console.log("Meeting is in future");
                }
            });

Output – Meeting is in future

Issue – Using this code I am getting meetings in future, but all the meeting time is actually past time. How can I resolve this issue?

Advertisement

Answer

new Date will take either format.

const d1 = new Date("Mon Jan 3 2022 16:38:58 GMT+0530 (India Standard Time)") 
const d2 = new Date("2022-01-03T18:30:00Z")
console.log(d1)
console.log(d2)

if (d1 < d2) console.log("Date 1 is earlier than d2")

// To find hh:mm:ss difference for the same day we can do this. 
console.log(new Date(d2-d1).toISOString().substr(11, 8))

If you want difference in days, hours etc, you will need more code easily found at SO

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement