PHP: How to compare a time string with date('H:i')? - php

I have time saved in database like 7:30pm as a varchar field. I want to check if this time is greater than time right now or not.
I converted the DB time string into '19:30' and now I want to do something like this:
$my_time = '19:30';
if($my_time > date('H:i'))
{
do something ...
}
The problem is the above will return always true if $my_time is non-empty string.
doing strtotime($my_time) is not helping either.
strtotime('H:i',$my_time) makes it 00:00 .
doing (int)date('H:i') will give 1700 when the actual time is 17:09, so removing colon and then comparing will not work too ....
Changing database time data is out of question in this context.
plz help. Correct me if I stated some facts wrong.

You can use this:
$myTime = '19:30';
if (date('H:i') == date('H:i', strtotime($myTime))) {
// do something
}

You can construct a new DateTime object, setting the time on a random date. Than compare those two objects. eg:
$my_time = new DateTime('January 1th 1970 19:30');
$comparable_time = new DateTime('January 1th 1970 '. date('H:i'));
if($my_time < $comparable_time) {
// do something
} else {
// do something else
}
Please take note of the changelog;
Version 5.2.2 DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).

You can't use the comparison operators with strings like that, because when you do the strings get converted to numbers first.
For an one-liner solution, you can use strcmp:
if(strcmp($my_time, date('H:i')) == 1)
{
do something ...
}
The condition above is semantically equivalent to "if $my_time is greater than the current time", but only if the format of the strings remains consistent! It's very easy to introduce a bug in this code if for any reason the format of $my_time does not directly correspond to the H:i pattern.
Dumbing down the values to strings is usually not the way you should be going about using dates and times. A more appropriate solution would be to use the native DateTime class, introduced in PHP 5.2.0 (John Conde has already given an example in his answer).
However, there is also one possible advantage to treating times as dumb scalar values: the results are consistent with the human perception that 01:00 is always later than 00:00. DateTime approaches are dependent on the local timezone and date, and might not always give you the expected results. Example:
// assume we are in London
date_default_timezone_set('Europe/London');
// assume that today is March 25, 2012
$date1 = new DateTime("2012-03-25 01:00:00");
$date2 = new DateTime("2012-03-25 02:00:00");
// and...
if ($date1 == $date2) {
echo "WTF?!? Equal???";
}
See it in action.
The result of this test is different than what comparing some scalar representation of "01:00" and "02:00", so it's a good idea to think about what the proper semantics are for the comparison.

$date1 = DateTime::createFromFormat('H:i', $my_time1);
$date2 = new DateTime();
if ($date1 > $date2)
{
// do something
}

Don't compare strings which represent timestamps. Instead, use strtotime() to convert any such strings to Unix timestamps, which are just numbers, and then compare these. You can get the Unix timestamp for the current time with time():
$my_time = '19:30';
if (strtotime($my_time) > time()) {
// do something ...
}

Related

Check if date is bigger than string [duplicate]

I have following
$var = "2010-01-21 00:00:00.0"
I'd like to compare this date against today's date (i.e. I'd like to know if this $var is before today or equals today or not)
What function would I need to use?
strtotime($var);
Turns it into a time value
time() - strtotime($var);
Gives you the seconds since $var
if((time()-(60*60*24)) < strtotime($var))
Will check if $var has been within the last day.
That format is perfectly appropriate for a standard string comparison e.g.
if ($date1 > $date2){
//Action
}
To get today's date in that format, simply use: date("Y-m-d H:i:s").
So:
$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";
if ($date < $today) {}
That's the beauty of that format: it orders nicely. Of course, that may be less efficient, depending on your exact circumstances, but it might also be a whole lot more convenient and lead to more maintainable code - we'd need to know more to truly make that judgement call.
For the correct timezone, you can use, for example,
date_default_timezone_set('America/New_York');
Click here to refer to the available PHP Timezones.
Here you go:
function isToday($time) // midnight second
{
return (strtotime($time) === strtotime('today'));
}
isToday('2010-01-22 00:00:00.0'); // true
Also, some more helper functions:
function isPast($time)
{
return (strtotime($time) < time());
}
function isFuture($time)
{
return (strtotime($time) > time());
}
You can use the DateTime class:
$past = new DateTime("2010-01-01 00:00:00");
$now = new DateTime();
$future = new DateTime("2021-01-01 00:00:00");
Comparison operators work*:
var_dump($past < $now); // bool(true)
var_dump($future < $now); // bool(false)
var_dump($now == $past); // bool(false)
var_dump($now == new DateTime()); // bool(true)
var_dump($now == $future); // bool(false)
var_dump($past > $now); // bool(false)
var_dump($future > $now); // bool(true)
It is also possible to grab the timestamp values from DateTime objects and compare them:
var_dump($past ->getTimestamp()); // int(1262286000)
var_dump($now ->getTimestamp()); // int(1431686228)
var_dump($future->getTimestamp()); // int(1577818800)
var_dump($past ->getTimestamp() < $now->getTimestamp()); // bool(true)
var_dump($future->getTimestamp() > $now->getTimestamp()); // bool(true)
* Note that === returns false when comparing two different DateTime objects even when they represent the same date.
To complete BoBby Jack, the use of DateTime OBject, if you have php 5.2.2+ :
if(new DateTime() > new DateTime($var)){
// $var is before today so use it
}
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09". Comparison involving timestamp will nullify the logic here. Example,
// input
$var = "2016-11-09 00:00:00.0";
// check if date is today or in the future
if ( time() <= strtotime($var) )
{
// This seems right, but if it's ONLY date you are after
// then the code might treat $var as past depending on
// the time.
}
The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:
// plain date string
$input = "2016-11-09";
Because the input is plain date string, using strtotime() on $input will assume that it's the midnight of 2016-11-09. So, running time() anytime after midnight will always treat $input as past, even though they are on the same day.
To fix this, you can simply code, like this:
if (date("Y-m-d") <= $input)
{
echo "Input date is equal to or greater than today.";
}
Few years later, I second Bobby Jack's observation that last 24 hrs is not today!!! And I am surprised that the answer was so much upvoted...
To compare if a certain date is less, equal or greater than another, first you need to turn them "down" to beginning of the day. In other words, make sure that you're talking about same 00:00:00 time in both dates.
This can be simply and elegantly done as:
strtotime("today") <=> strtotime($var)
if $var has the time part on 00:00:00 like the OP specified.
Replace <=> with whatever you need (or keep it like this in php 7)
Also, obviously, we're talking about same timezone for both.
For list of supported TimeZones
$date1=date_create("2014-07-02");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
(the w3schools example, it works perfect)
Expanding on Josua's answer from w3schools:
//create objects for the dates to compare
$date1=date_create($someDate);
$date2=date_create(date("Y-m-d"));
$diff=date_diff($date1,$date2);
//now convert the $diff object to type integer
$intDiff = $diff->format("%R%a");
$intDiff = intval($intDiff);
//now compare the two dates
if ($intDiff > 0) {echo '$date1 is in the past';}
else {echo 'date1 is today or in the future';}
I hope this helps. My first post on stackoverflow!
Some given answers don't have in consideration the current day!
Here it is my proposal.
$var = "2010-01-21 00:00:00.0"
$given_date = new \DateTime($var);
if ($given_date == new \DateTime('today')) {
//today
}
if ($given_date < new \DateTime('today')) {
//past
}
if ($given_date > new \DateTime('today')) {
//future
}
Compare date time objects:
(I picked 10 days - Anything older than 10 days is "OLD", else "NEW")
$now = new DateTime();
$yourdate = new DateTime("2021-08-24");
$diff=date_diff($yourdate,$now);
$diff_days = $diff->format("%a");
if($diff_days > 10){
echo "OLD! " . $yourdate->format('m/d/Y');
}else{
echo "NEW! " . $yourdate->format('m/d/Y');
}
If you do things with time and dates Carbon is you best friend;
Install the package then:
$theDay = Carbon::make("2010-01-21 00:00:00.0");
$theDay->isToday();
$theDay->isPast();
$theDay->isFuture();
if($theDay->lt(Carbon::today()) || $theDay->gt(Carbon::today()))
lt = less than,
gt = greater than
As in the question:
$theDay->gt(Carbon::today()) ? true : false;
and much more;
Try this:
if (date("Y-m-d",strtotime($funding_dt)) >= date("Y-m-d",strtotime('31-01-2007')))
{
echo "ok";
} else {
echo "not";
}

Comparing actual date with other date

I have this
$fecha_actual = strtotime('now');
$fechaactual = date("d/m/Y",$fecha_actual);
$fechatope = $fila1['fechatope'];
if($fechatope < $fechaactual) {
echo "Fecha Actual: $fechaactual y Fecha Tope: $fechatope ";
}
The result I obtain:
Fecha Actual: 03/10/2018 y Fecha Tope: 03/02/2019
Why enter on the if when $fechatope is bigger than $fechaactual?
I dont understand...
Try to compare them with
strtotime($fechatope) < strtotime($fechaactual)
This way it just compares integers, less error chances.
In PHP, the date function returns a string. So your variable $fechaactual is the string
"03/10/2018"
Now I'm guessing your variable $fechatope is the string
"03/02/2019"
If you do a string comparison, $fechaactual is greater!
This is why most programmers these days do not use country-specific date formats. If you are going to compare strings, use the international date format, ISO 8601, and not a country's specific format. ISO 8601 allows sorting on strings, because it is YYYY-MM-DD. Formats that are day-first or month-first are bad for programming. (End of rant! :) )
Alternatively, you can compare date objects themselves, or reduce each date to an epoch time.
Dates are hard.
Try this
$fecha_actual = strtotime('now');
$fechaactual = date("d/m/Y",$fecha_actual);
$fechatope = date("d/m/Y",strtotime($fila1['fechatope']));
if($fechatope < $fechaactual) {
echo "Fecha Actual: $fechaactual y Fecha Tope: $fechatope ";
}
date() returns a string. So you are comparing if a string is less than another string (I'm assuming the type of the second parameter since we don't see it).
There are many special rules when it comes to comparison of strings with < and > in PHP. It will compare strings based upon alphabetical order. If a string starts with a number that number will use in the comparison and so on.
No matter what, this is most likely not what you expect.
Either, you could turn both times into timestamps which are both numerical and can be compared as in your code. Or you could turn the strings into DateTime objects and use the DateTime::diff function or boolean operators like <, > and == to compare the dates.
Assuming you have a string 03/02/2019 and you want to compare it with current time:
$fechaactual = new DateTime(); // current date and time
$fechatope = DateTime::createFromFormat("m/d/Y|", "03/02/2019"); // 2019-03-02 00:00:00
var_dump($fechaactual < $fechatope); // true
var_dump($fechaactual == $fechatope); // false (warning: dont use ===)
var_dump($fechaactual > $fechatope); // false
This looks far more complicated solution that others but it is the most versatile. It leaves no ambiguity as long as you know the date format(s) involved.
This is because in your given example, by comparison your Fecha Tope IS smaller than your Fecha Actual.
WHY?
Because of your date format. Imagine the PHP code working out whether one date is bigger or smaller than the other. It does so by calculating it like an integer.
So let's convert our dates to integers:
Fecha Actual = 03102018
Fecha Tope = 03022019
Now because your date is formatted as day, month, year - it doesn't matter much if there is a year difference, because that will be the smallest unit in our integer value. Whereas a difference in a day will result in the largest unit changes.
If you reorganise your code, and from now on use "Y-m-d" then you will avoid this problem when comparing dates.
Since date() returns a string, you will have to format it. You will also need to abide by the programmatical standards for time, which is Y-m-d, and not your country-specific standards.
Assuming you are fetching another date (the one you compare it with) from the database, you will have to format that string to time as well, using the strtotime() function.
Example:
$dateExample=date('d/m/Y'); // your date() string
$format = "d/m/Y"; // current string format to change.
$timedate = DateTime::createFromFormat($format, $dateExample); //creates the format and changes the string to a dateTime object.
$dateExample = $timedate->format('Y-m-d'); //perform the format, changing the standard to Y-m-d format.
$anotherDateFromDataBase = $row['dateColumn']; //date variable fetched from the database
$anotherDateFromDataBase = strtotime($anotherDateFromDataBase); //converts the string to time
You can now compare the two dates.
if($anotherDateFromDataBase < $dateExample) {
//do something
}

Hiding a link depending on date in PHP

I am displaying a number of dates using PHP and I need to hide them when a certain date has expired.
I am using an IF statement to run this but it doesn't seem to be working.
Any suggestions would be great
<?PHP if('09-19-2016'<DATE('m-d-Y') || $_SESSION['role'] == 'Administrator') echo('<li>Week 2 - W/C 12/09/2016</li>');?>
When you're doing
'09-19-2016' < date('m-d-Y')
You're ending up comparing two strings, these can't be evaluated as "greater than" or "less than". You'll need to convert it to timestamps or use DateTime objects to do it. Also, the date format isn't correct.
<?php
$date_string = "09/19/2016";
// Using objects
$current_date = new DateTime();
$your_date = new DateTime($date_string);
if ($your_date < $current_date || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
// Using timestamps
if (strtotime($date_string) < time() || $_SESSION['role'] == 'Administrator')
echo'<li>Week 2 - W/C 12/09/2016</li>';
Choose either one of the above - both will work, although I find objects easier to work with.
From your comments,
hide the date if the date has passed
Note that when using the less than operator <, doing $date < $now will evaluate to true if the date is in the past, and hide the content if the date is in the future. If you desire the opposite behavior, you just use the greater than operator <.
Here's a live demo: https://3v4l.org/N74G2
References
http://php.net/datetime.construct
http://php.net/strtotime
http://php.net/language.operators.comparison
You need to parse your date from your format '09-19-2016' to a timestamp or DateTime object, which PHP will be able to compare as a date. You can use PHP's date_parse_from_format() to do so.
For example:
$date = '09-19-2017';
$parsed = date_parse_from_format('m-d-Y', $date);
$timestamp = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
if ($timestamp < time()) {
echo 'older';
} else {
echo 'newer';
}
This will give you the correct answer while keeping your current format. You can see an working example here: https://3v4l.org/NIoId

php strtotime() values not working as expected

this code keeps telling me that $lasUpdate is always greater than $yesterday no matter the change i make to $yesterday result is (12/31/14 is greater than 01/19/15 no update needed). i feel like i'm missing something simple thank you in advance it is greatly appreciated.
$result['MAX(Date)']='12/31/14';
$lastUpdate = date('m/d/y', strtotime($result['MAX(Date)']));
$yesterday = date('m/d/y', strtotime('-1 day'));
if($lastUpdate<$yesterday){echo $lastUpdate.'is less '.$yesterday.'<br>'.'update needed';}
if($lastUpdate>=$yesterday){echo $lastUpdate.'is greater than '.$yesterday.'<br>'.'no update needed';
You have fallen victim to PHP type juggling with strings. A date function has a return value of a string. You cannot compare dates in their string format since PHP will juggle strings into integers in the context of a comparison. The only exception is if the string is a valid number. In essence, you are doing:
if ('12/31/14' < '01/19/15') { ... }
if ('12/31/14' >= '01/19/15') { ... }
Which PHP type juggles to:
if (12 < 1) { ... }
if (12 >= 1) { ... }
And returns false on the first instance, and true on the second instance.
Your solution is to not wrap date around the strtotime functions, and just use the returned timestamps from the strtotime functions themselves to compare UNIX timestamps directly:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
You will however want to use date when you do the echo back to the user so they have a meaningful date string to work with.
Try something like this:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
if ($lastUpdate < $yesterday) { /* do Something */ }
12/31/14 is greater than 01/19/15
Because 1 is greater than 0. If you want to compare dates that way you will need to store them in a different format (from most to least significant digit), for example Ymd.
Or store the timestamps you are making in the different variables and compare them.

Year comparison in PHP

if($_POST['syear']){
$compy = strtotime($_POST['syear']);
if(date("Y") <= date("Y", $compy)){
//success
$startdate = $_POST['syear'];
}
else{
$error = 6;
}
}
I have created the above code and have no idea where I have gone wrong. I am posting a string from a form with a number in it and want to compare it to the current year. If the number is equal to or less than the current year it is supposed to be a success. It is always a success even if the number is larger than the current year. Do I need to convert some strings to ints or have I missed something entirely.
PHP handle string comparison very well, did you try this directly ? (and changing the comparison order to >=)
if($_POST['syear']){
if(date("Y") >= $_POST['syear']){
$startdate = $_POST['syear'];
}else{
$error = 6;
}
}
You cannot convert simply a year to time. Using your example as is, you need to have a string of yyyy/mm/dd format to use strtotime. If you are really just checking year, you can use January 1st as a check date.
$compy = strtotime($_POST['syear'] . '-01-01' );
You can compare integers or strings the same way. If you want to be sure about the type comparison you can always cast the variable but in this case it's pointless.
2012 is inferior to 2013. "2012" is inferior to "2013". date( 'Y' ) returns a 4 characters string you can compare with your $_POST['syear'] if it's a 4 character string. Hope this helps.
You could try
if(time() <= $compy){
since your already doing strtotime() on whatever compy is originally. This way your working with 2 unix timestamps and comparing them that way.

Categories