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
Related
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";
}
I'm trying to do a simple if echo statement.
<?php if (time("mm-dd") > strtotime("11-01") && time("mm-dd") < strtotime("02-28"))echo 'stuff' ?>
Basically I want to echo something if today is either Nov, Dec, Jan, Feb. The code works if I use time() and the full year but I'd like to just compare the month, day. I think I have some silly syntax error that I just can't figure out. This code snippet is placed in the <head> of my html if that makes a difference. Little help. Thanks.
This is what I ended up with. Thanks!
<?php if ($today > '12-16' || $today < '01-08') echo 'yes' ?>
with $today = date("m-d")
Use the date function instead of time.
Switch && to ||. No m-d date string will ever be both greater than 11-01 and less than 02-28.
You probably want to use an inclusive comparison operator with November 1 and an exclusive one against March 1 to account for leap years.
Instead of calling date() twice, why not assign the result to a variable?
Here it is all together:
$today = date('m-d');
if ($today >= '11-01' || $today < '03-01') { ... }
Consider using date checking the month only:
$month = (int) date("m");
$isMonthCorrect = $month === 11 || $month === 12 || $month === 1 || $month === 2;
Note the importance of (int). Integer comparisons are more reliable than string comparisons, even if they behave similarly.
Or if you want to check between two dates, to optimize performance, you should evaluate the dates into timestamps before putting them in code.
For example, you can use some websites for converting Unix timestamps. (Not gonna advertise any here, but you can search "Unix timestamp converter) You can also use php -r to get quick output:
php -r 'echo strtotime("2016-11-01 00:00:00");'
php -r 'echo strtotime("2017-02-01 00:00:00");'
Then you can use them like this:
$minimum = 1477958400; // from first command line
$maximum = 1485907200; // from second command line
$isInPeriod = $minimum <= time() && time() <= $maximum;
Keep in mind:
time() always returns the current Unix timestamp, i.e. number of seconds since the Unix Epoch. Use strtotime for converting a string to time, and use date() to convert a timestamp to a string in a given format.
Unix timestamp is always absolute. You can't convert a "month" into a Unix timestamp. You can only obtain the current Unix timestamp with time(), or get specific data from the timestamp using date().
References:
strtotime
time
date
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.
I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}
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";
}