I want to find the difference between two dates and I have used date_diff for the same. When format function is applied on date_diff object it returns an error.
Call to a member function format() on boolean
$field_value is fetched from the database and it's format is dd/mm/YYYY. When I hard-code the values for $field_value and $indexing_value the following code works.
Everything is running fine till line number 8. I have tried outputting the value of
$diff->format("%R%a")
and it is returning exact value but the code gives error near the if statement.
$date = new DateTime();
$current_date = $date->format('d/m/Y');
$indexing_value = str_replace("/", "-", $field_value);
$current_value = str_replace("/", "-", $current_date);
$indexing_value = date_create($indexing_value);
$current_value = date_create($current_value);
$diff = date_diff($indexing_value, $current_value);
if ($diff->format("%R%a") < 0) {
echo "1";
} else {
echo "2";
}
Please let me know what is wrong with the above code.
add condition to check whether you got the diff or not, as it returns false if there is error . Check manual for the same
$diff = date_diff($indexing_value, $current_value);
if ($diff) {
if ($diff->format("%R%a") < 0) {
echo "1";
}else{
echo "2";
}
}
You are getting error because for some values the diff is not calculated and have value False in $diff
Please let me know what is wrong with the above code.
There are several issues with the code:
You don't check the values returned by date_create(); it returns FALSE on error.
What's the point of formatting $date then creating $current_value back from the resulting string? If you don't care about the time components and need to use only the date part of a DateTime object you can use its setTime() method to set the time components to 0.
What's the point of using str_replace() to manipulate the text representation of a date when you know its format? DateTime::createFromFormat() can be used to parse the string into a DateTime object.
There is no need to compute the difference of the two dates and the format it and compare the value to 0. The DateTime objects can be compared directly.
All in all, all the code you need is:
// Current date & time
$today = new DateTime();
// Ignore the time (change $today to "today at midnight")
$today->setTime(0, 0, 0);
// Parse the value retrieved from the database
$field = DateTime::createFromFormat('d/m/Y', $field_value);
// We don't care about the time components of $field either (because the time
// is not provided in the input string it is created using the current time)
$field->setTime(0, 0, 0);
// Directly compare the DateTime objects to see which date is before the other
if ($field < $today) {
echo "1";
} else {
echo "2";
}
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 have a js calendar in an HTML page and I'm passing the picked date into a PHP file. Currently, the date field is mandatory and it will display the default 1970/01/01 if no date is picked in the calendar.
I'm trying to change the behavior so that when no date is picked, then the current date will be passed into the PHP file.
The code in the PHP file is the one below:
$mydate = strtotime($_POST['mydate']);
$mydate = date("Y/m/d",$mydate);
How can I change it in order to display the current date if there's no value passed from $_POST['mydate']?
PS: I'm a newbie to PHP functions and searching for similar cases in the forums did not help.
The reason you get that is because strtotime returns false if it can't parse the date.
False is typecasted to 0, and date of 0 is 1970.
What you can do is to check if the strtotime return is false. (Not the same as isset or 0 in my opinion).
$mydate = strtotime($_POST['mydate']);
if($mydate === false){ // === is strict comparison
$mydate = date("Y/m/d");
}else{
$mydate = date("Y/m/d",$mydate);
}
Try this:
if( empty( $_POST['mydate'])){
$mydate = date("Y/m/d");
} elseif( FALSE !== $tm = strtotime( $_POST['mydate'])) {
$mydate = date("Y/m/d", $tm);
} else {
$mydate = date("Y/m/d");
}
I am trying to find the difference between two datetime objects, in this case the difference between the current date ($nowDate) and the result I've pulled from a datetime column in MySql ($row['dueDate]' , or $rowDate). I have set the value in MySql to datetime and I am trying to subtract that time I pull by the current date as represented as a DateTime object. The problem is that I have tried to convert what I get from MySQL into a DateTime object but
I've tried first using the ::createFromFormat option to try to wrangle the sql output into a usable format, but a php error is thrown claiming the result is a boolean. When I try using strtotime the error thrown claims it is an integer, and when I try to use the output from the program PHP claims it's a string!
Code below:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE"; //
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
var_dump($row['dueDate']);
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
date_default_timezone_set('America/Vancouver');
//$nowDate = date("Y-m-d H:i:s");
$nowDate = new DateTime;
var_dump($nowDate); //tests positive- outputting current time
$rowDate = strtotime($row['dueDate']); //WHY ISN'T THIS GIVING ME A DATETIME TYPE???
$D = 1 / (date_diff($nowDate, $rowDate)); //ERROR
//supposed to put the most recent date first!
How do I get the $rowDate variable to be of the dateTime type and not something else?
The date_diff() needs two DateTimeInterface objects as arguments.
$nowDate = new DateTime ;
$rowDate = new DateTime("2018-01-05") ;
$diff = date_diff($nowDate, $rowDate) ;
Then $diff is now a DateInterval, not a numeric value. But you can use seconds or microseconds, by example :
$seconds = $diff->s ; // integer value
$microseconds = $diff->f ; // float value
The first date is today's date and the second one is being retrieved from a DB. The purpose of what I'm trying to do is that I want to trigger an alert 7 days before the due date, which is the date stored in the DB.
I have tried to figure this out a few different ways without any success. I started by using the strtotime function to subtract days from the retrieved date and then compare it to today's date. Here is my first try:
$date1 = strtotime(date('2013-11-14',strtotime('-7 days')));
$date2 = strtotime(date('Y-m-d'));
$check = $date1 - $date2;
$check = date('j',$check);
if($check <= 7){echo "Under 1 week";}
But that doesn't work because it doesn't take into account the month, only the day...so 2013-12-14 will return the same result as 2013-11-13.
So then I tried:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('now');
$interval = $datetime1->diff($datetime2);
$interval->format('%a');
if($interval <= 7){echo "Under 1 week";}
But then I get an error:
*Object of class DateInterval could not be converted to int*
I figured that a number was an integer no matter what, but I've now learned that isn't the case.
I have done a lot of searching on the internet, because I'm sure someone else has been trying to do this same thing and I found this helpful bit of code that works perfectly:
function e_days($end,$start) {
/************************************************************************/
/* Purpose: To get the elapsed days of date diff as integer. */
/************************************************************************/
$dtS = new DateTime($start);
$dtE = new DateTime($end);
$int = $dtE->diff($dtS);
$ret = (integer) $int->format('%a');
return $ret;
} // end function
Normally I would just carry on and be happy, but I don't like to just use something I found without understanding it. The part I don't understand is this line:
$ret = (integer) $int->format('%a');
What is "(integer)" ? I assume it must change the number to an integer but I can't find it on php.net listed as a function.
I would also like to know if there is another way to do this, or if this guy nailed it.
Function Credit: OldManRiver
(integer) casts whatever immediate follows it as an int type. In your case, it casts $int->format('%a') into an integer.
Consider the following (int is an alias for integer):
$str = "10";
$num = (int)$str;
if ($str === 10) echo "String";
if ($num === 10) echo "Integer";
In the example above, $int = $dtE->diff($dtS), so int is the difference between two DateTime objects in DateTime format. According to the documentation, format('%a') returns the total number of days between the two objects. Casting the return value using (integer) ensures that it will be an int type.
UPDATE:
More info on type-casting can be found here (for integers) and here (for general "type juggling").
From the docs:
To explicitly convert a value to integer, use either the (int) or (integer) casts.
(int), (integer) - cast to integer
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";
}