简体   繁体   中英

How to find difference between two dates obtained as a response from PHP? I'm storing the response dates in two javascript variables

function chatbox($to_user_id,to_name,from_name,$from_user_id,$user_last_activity) 
{
    var to_user_id = $to_user_id;
    var from_user_id = $from_user_id;
    var status = "";
    var last_seen = $user_last_activity;
    var current_time = "<?php
                          echo $current_timestamp = date("Y-m-d H:i:s");
                        ?>"; 
}

I am fetching $user_last_activity from database using php and passing it to the javascript function chatbox. And i am getting the current time from php date function. How to compare these two javascript variable to get the time difference in sec, min and hour.

Please use php as

<script>
var date= "<?php echo $current_timestamp = date('Y-m-d H:i:s'); ?>";
</script>

Remember you can't use " in ' ' string and ' in " " string because it will consider the string end point.

Once you fix the quote issue, there is another issue here:

$current_timestamp = date("Y-m-d H:i:s")

That will produce a timestamp in the format (using moment.js tokens) YYYY-MM-DD HH:mm:ss (eg 2020-03-08 16:38:21), which is not supported by ECMA-262. You don't show how the timestamp is converted to a Date, but I'll guess you're using the built–in parser like:

var d = new Date(current_time);

However, since parsing of unsupported formats is implementation dependent, some browsers will return an invalid date.

Also, the PHP code produces a "local" date for the server, presumably it's set to UTC. Where browsers do parse a date in the format YYYY-MM-DD HH:mm:ss, it will almost certainly be as local to the browser's host system so will represent a different moment in time from the initial timestamp if the two systems have different settings.

The OP doesn't say what format $user_last_activity is. Presumably it's another timestamp, so it will have the same issues with parsing.

Once the above issues are sorted, you can get the difference in milliseconds between two dates by simply subtracting one from the other, see Difference between dates in JavaScript . The time difference can then be converted to days, hours, minutes, whatever.

I have solved it by changing the logic. I just used strtotime() to both $user_last_activity and $current_time in the php page from where i'm calling JavaScript chatbox() function and find the difference there and then passing the difference in the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM