Ask Your Question
2

How to calculate the time difference between two timestamps using PHP?

asked 2023-06-06 17:05:19 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-06 17:28:02 +0000

bukephalos gravatar image

You can use the strtotime() function to convert the timestamps into Unix timestamps and then subtract them to get the time difference in seconds. Here's an example:

$timestamp1 = '2020-12-01 08:30:00';
$timestamp2 = '2020-12-01 09:15:30';

$time1 = strtotime($timestamp1);
$time2 = strtotime($timestamp2);
$timeDiff = $time2 - $time1;

echo "Time difference: " . $timeDiff . " seconds";

This will output:

Time difference: 2730 seconds

To convert the time difference into minutes, hours, or days, you can divide it by the appropriate factor:

$minutesDiff = $timeDiff / 60;
$hoursDiff = $timeDiff / (60 * 60);
$daysDiff = $timeDiff / (60 * 60 * 24);

Keep in mind that these calculations are based on the Unix timestamp, which is the number of seconds since January 1, 1970. If your timestamps are in a different format or time zone, you may need to adjust the calculations accordingly.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 17:05:19 +0000

Seen: 14 times

Last updated: Jun 06 '23