Home > Backend Development > PHP Tutorial > How to Compare Times in PHP and Fix a Common Error?

How to Compare Times in PHP and Fix a Common Error?

Barbara Streisand
Release: 2024-11-07 12:30:03
Original
865 people have browsed it

How to Compare Times in PHP and Fix a Common Error?

Comparing Times in PHP

In PHP, comparing times can be achieved using different approaches. Let's explore them and resolve a specific issue in comparing times.

Problem:
The given code fails to compare time correctly and output "ok" as expected:

$ThatTime ="14:08:10";
$todaydate = date('Y-m-d');
$time_now=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_now);
if($NowisTime >= $ThatTime) {
    echo "ok";
}
Copy after login

Solution 1:
Use the strtotime() function to convert the time string to a timestamp:

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}
Copy after login

Solution 2:
Utilize the DateTime class, which also considers time zones:

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}
Copy after login

Reference:
https://php.net/datetime.diff

The above is the detailed content of How to Compare Times in PHP and Fix a Common Error?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template