Comparing time, hh:mm and h:mm in PHP

php datetime
php time difference in hours
php strtotime
php datetime format
php compare dates greater than
php time difference in seconds
how to compare two dates in php mysql
php compare datetime

I am having a problem with comparing hh:mm and h:mm, example code below. Please note that this is an example, in actual fact, I am retrieving data from the database.

This code checks for hh:mm and h:mm time format using pregex and also checks if $EndTime is earlier than $StartTime it will echo 'Time Error', basically EndTime cannot be earlier than StartTime (EndTime should be later than StartTime). So if either one of the checks is true, it will echo 'Time Error'.

$StartTime = '8:00';
$EndTime = '19:00';
if(!preg_match("/^(?:2[0-3]|[01][0-9]|[0-9]):[0-5][0-9]$/", $StartTime) || ($StartTime > $EndTime)){
    echo 'Time Error';
}
else{
    echo 'Time Correct';
}

The above code will echo 'Time Error' is if I use 8:00 as my StartTime. However, if I use 08:00 as my StartTime it will echo 'Time Correct'.

if I change it to:

$StartTime = '19:00';
$EndTime = '8:00';

It will echo 'Time Correct', which should not be the case as EndTime is earlier than StartTime. Same thing, if I change it to 08:00 it show me the correct message.

Checked pregex for 8:00 and 08:00 and both are correct time format.

Why is it so and how do I fix this error? Is there something wrong with the comparing of time?

Thanks in advance for any help rendered.

Thank you Lucas Arbex for the strtotime suggestion. It seems to work now.

$startTime = ('00:00');
$endTime = ('08:00');

if((!preg_match("/^(?:2[0-3]|[01][0-9]|[0-9]):[0-5][0-9]$/", $startTime)) || (strtotime($startTime) > strtotime($endTime)) || (!preg_match("/^(?:2[0-3]|[01][0-9]|[0-9]):[0-5][0-9]$/", $EndTime))){
  echo 'Time Error';
}
else{
  echo 'Time Correct';
}

Do the format checking separate from the time comparison. Add a leading zero if the time doesn't already have one.

if(!preg_match("/^(?:2[0-3]|[01][0-9]|[0-9]):[0-5][0-9]$/", $StartTime) || !preg_match("/^(?:2[0-3]|[01][0-9]|[0-9]):[0-5][0-9]$/", $EndTime)){
    echo 'Time Error';
} else {
    if ($StartTime[1] == ":") {
        $StartTime = "0" . $StartTime;
    }
    if ($EndTime[1] == ":") {
        $EndTime = "0" . $EndTime;
    }
    if ($StartTime > $EndTime) {
        echo 'Time Error';
    } else {
        echo 'Time Correct';
    }
}

DateTime::diff - Manual, As of PHP 5.2.2, DateTime objects can be compared using comparison operators​. The task was to calculate the duration between two date/times. birthdate format is YYYY-MM-DD echo "Difference between ".date('Y-m-d H:i:s',$date1). Module Example Public Sub Main() Dim date1 As Date = #08/01/2009 12:00AM# Dim date2 As Date = #08/01/2009 12:00PM# Dim result As Integer = DateTime.Compare(date1, date2) Dim relationship As String If result < 0 Then relationship = "is earlier than" ElseIf result = 0 Then relationship = "is the same time as" Else relationship = "is later than" End If Console.WriteLine("{0} {1} {2}", date1


You can validate the incoming time expressions and check for the optional leading zero within the regex pattern. There is no need to make the extra strtotime() calls.

Code: (PHP Demo) (Regex Demo)

$startTime = '19:00';
$endTime = '8:00';

if (!preg_match("~^(?|(2)\K[0-3]|([01]?)\K\d):[0-5]\d$~", $startTime, $start) || 
    !preg_match("~^(?|(2)\K[0-3]|([01]?)\K\d):[0-5]\d$~", $endTime, $end) ||
    (int)$start[1] . $start[0] > (int)$end[1] . $end[0]
) {
        // var_export($start);
    echo "\nTime Error\n";
        // var_export(((int)$start[1] . $start[0]) . ' versus ' . ((int)$end[1] . $end[0]));
}
// outputs: Time Error

The above technique uses a pattern that captures the hour digit (optional if trailed immediately by another digit), then restarts the fulstring match with \K. A "branch reset" (|...|...) is used to make sure that both capture groups are treated as element [1] in the match array. By making the leading digit optional, you can omit the third branch in your original pattern. Also, I prefer the shorter \d over [0-9].


If this is too messy|complicated for you, you could also consider allowing php to compare the two strings as float values.

Code: (PHP Demo)

if (!preg_match("~^(?:2[0-3]|[01]?\d):[0-5]\d$~", $startTime) || 
    !preg_match("~^(?:2[0-3]|[01]?\d):[0-5]\d$~", $endTime) ||
    str_replace(':', '.', $startTime) > str_replace(':', '.', $endTime)
) {
    echo "\nTime Error\n";
        // var_export(str_replace(':', '.', $startTime) . ' versus ' . str_replace(':', '.', $endTime));
}

And of course, you can unconditionally apply left-side padding with zeros. (As you can see, there are many ways to skin this cat.)

if (!preg_match("~^(?:2[0-3]|[01]?\d):[0-5]\d$~", $startTime) || 
    !preg_match("~^(?:2[0-3]|[01]?\d):[0-5]\d$~", $endTime) ||
    str_pad($startTime, 5, 0, STR_PAD_LEFT) > str_pad($endTime, 5, 0, STR_PAD_LEFT)
) {
    echo "\nTime Error\n";
        // var_export(str_replace(':', '.', $startTime) . ' versus ' . str_replace(':', '.', $endTime));
}

strtotime - Manual, Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or previous to PHP 5.1.0 you would compare with -1, instead of false echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp); } ?> To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or  For example: Cell A1 has a time format (hh:mm) value of 04:00; which is the Start Time. I would like cell D1 to have a text format value of "04:00" (result is dependant upon what is entered in A1). I would duplicate the same formulas to reflect Stop Times in other cells.


You can simply use strtotime() to parse the string into datetime after the validation, like so:

$starttime = '19:00';
$endtime = '8:00';

$validatedStarttime = preg_match("/([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?/", $starttime);
$validatedEndtime = preg_match("/([01]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?/", $endtime);

if($validatedStarttime && $validatedEndtime) {
    if(strtotime($starttime) > strtotime($endtime)) {
        echo 'Time Error';
    } else {
        echo 'Time Correct';
    }
} else {
    echo 'Incorrect Format';
}

Let me know if this helped you.

strftime - Manual, strftime — Format a local time/date according to locale settings %h, Abbreviated month name, based on the locale (an alias of %b), Jan through Dec. %m, Two  Comparing time, hh:mm and h:mm in PHP. Ask Question Asked 1 month ago. Active 1 month ago. Viewed 67 times -1. I am having a problem with comparing hh:mm


DateTime::createFromFormat - Manual, public static DateTime::createFromFormat ( string $format , string $time [ G and H, 24-hour format of an hour with or without leading zeros, 0 through 23 or 00 day, hour, minute, second, fraction and timezone information) to the Unix Epoch if If you want to safely compare equality of a DateTime object without explicitly  It stores not just the date, but also the time: YYYY-MM-DD HH:MM:SS, where HH is hours, MM is minutes, and SS is seconds. Note that HH uses 24-hour time — the range is from 00 to 23. (SQL Server also includes optional fractions of a second, like this: YYYY-MM-DD hh:mm:ss[.nnn], where .nnn is a decimal fraction of a second with an upper range


Comparing Dates in PHP and MySQL · Martin Thoma, PHP knows these time / date formats: int mktime([ int \$hour = date("H") [, int \$​minute = date("i") [, int \$second ( string \$time [, int \$now ] ) I recommend using YYYY-MM-DD HH:mm:ss if possible. Hey All, I imported the data from AS400. The values in the time field are for example like this: 92418, 130827. I have to convert them into 9:24:18, 13:08:27 respectively.


A simple PHP API extension for DateTime., $date = Carbon::createFromIsoFormat('!YYYY-MMMM-D h:mm:ss a', '2019-​January-3 6:33:24 pm', 'UTC'); echo $date->isoFormat('M/D/YY HH:mm'); // 1/3/19​  Javascript Compare dates. In the previous section, we discussed the date methods as well as the constructors. Here, with the help of those methods, we will learn to compare dates. Basically, there are different ways by which we can compare dates, such as: Comparing two dates with one another. Comparing date with time. Comparing dates using