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

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-07 12:30:03736browse

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";
}

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

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

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

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

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!

Statement:
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