Home > Net >  subtract mysql old time from now time using java script new Date function
subtract mysql old time from now time using java script new Date function

Time:10-19

I have imported time from MySQL and I want to subtract it from now time using java script, the code I have used below, but the result I got is "invalid Date". you can see my time table below.

 setInterval(function(){
    $(document).ready(function () {
        $.ajax({
       url: "plate.php",
       method:"GET",
        dataType:"JSON",
       success: function (data) {
           var id = [];
           var Time = [];
           var tp5 = [];
           for (var i in data){
              var oldtime = ((data[i].Time)); 
              console.log(data[i].id);
              console.log(data[i].tp5); 
              var nowtime= new Date();
              console.log(today);  
              var newDateObj = new Date(nowtime- oldtime);
            document.getElementById("datetime").innerHTML = newDateObj;
          }
        }
    });
});
        },  6000);

enter image description here

CodePudding user response:

oldtime should be a JS Date object.

Change:

var oldtime = ((data[i].Time)); 

To:

// date and time parts
let odp = data[i].Date.split("-");
let otp = data[i].Time.split(":");

let oldDate = new Date(odp[0], odp[1], odp[2], otp[0], otp[1], otp[2]);

Then you can get the difference between them with getTime

  • Related