Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get time difference between two strtotime datetime/s in hh:mm:ss format in PHP

i want to calculate the time difference between two strtotime datetime/s in hh:mm:ss format.

It is wordpress project. (PHP)

$target_time = strtotime($quiz_date . " 08:30 PM"); // Quiz Start time
$submitted_time = strtotime('now'); // submitted time
$time = gmdate('H:i:s', ($submitted_time - $target_time)); // difference in hh:mm:ss

I also set the desired default timezone.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

These are the datetimes when form is processing.

2023-08-29 20:30:00

2023-08-31 19:00:00

and it is inserting this as time 22:30:00

later i will insert the difference in ‘hh:mm:ss’ format to MySQL.

$query = "INSERT INTO Results (user_id, Time) VALUES (" . $user_id . " , " . $time . ");" ; 

>Solution :

The best way for me to solve this problem would be :

$quiz_date = date('Y-m-d', strtotime($quiz_date)) . " 08:30 PM";

$target_time = strtotime($quiz_date); 
$submitted_time = time(); 
$time_difference = $submitted_time - $target_time;

$hours = floor($time_difference / 3600);
$minutes = floor(($time_difference % 3600) / 60);
$seconds = $time_difference % 60;

$time_diff_formatted = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);

The idea is pretty clear I think, I just converted the $time_difference to hours, minutes and seconds! And this way you have the variable you need for the MYSQL Query!

Good luck!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading