Comparing Date from PHP to MYSQL, strtotime not working - php

I have a DATE field on my MySQL table. Let's say the value is 2015-05-05.
I would like to check if the current time is before or after that.
This is my code:
foreach ($row as $row)
{
$ExpDate = strtotime($row['exp_date']);
$Today = strtotime(date("Y-m-d"));
echo $Today . ' - ' . $ExpDate;
if ($Today > $ExpDate)
{
exit('<M>LicenseExpired<M>');
}
}
The problem is that it's not working. The value of exp without strtotime is 2015-05-05. It I add the strtotime, the value becomes an empty string.
How am I able to solve this problem or what would be a good way to compare dates in PHP?

When comparing dates in MySQL there is no reason to take the extra step and use string_to_time(). The below example should work just fine. The format of MySQL DATE is designed in such a way that comparisons of this nature work naturally without any extra steps needed.
foreach ($row as $row)
{
$ExpDate = $row['exp_date'];
$Today = date("Y-m-d");
echo $Today . ' - ' . $ExpDate;
if ($Today > $ExpDate)
{
exit('<M>LicenseExpired<M>');
}
}

try this
foreach ($row as $row)
{
$ExpDate = new DateTime($row['exp_date']);
$Today = new DateTime(date("Y-m-d"));
$interval = $ExpDate->diff($Today);
//echo $interval->format('%R%a days'); <--- to diffenernce by days.
if ($interval > 0)
{
exit('<M>LicenseExpired<M>');
}
}

Related

PHP Dates Condition [duplicate]

How can I compare two dates in PHP?
The date is stored in the database in the following format
2011-10-2
If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?
I tried this,
$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
but it doesn't really work that way. What's another way of doing it?
If all your dates are posterior to the 1st of January of 1970, you could use something like:
$today = date("Y-m-d");
$expire = $row->expireDate; //from database
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { /* do Something */ }
If you are using PHP 5 >= 5.2.0, you could use the DateTime class:
$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);
if ($expire_dt < $today_dt) { /* Do something */ }
Or something along these lines.
in the database the date looks like this 2011-10-2
Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.
Just to compliment the already given answers, see the following example:
$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database
if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) {
//do something;
}
Update:
Or simple use old-school date() function:
if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
//echo not yet expired!
}
I would'nt do this with PHP.
A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types
SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
Here's a way on how to get the difference between two dates in minutes.
// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));
// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;
echo $difference_in_minutes;
You can convert the dates into UNIX timestamps and compare the difference between them in seconds.
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
{
echo "Enter a valid date";
}
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
Here's my spin on how to get the difference in days between two dates with PHP.
Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.
$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";
Found the answer on a blog and it's as simple as:
strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
And you'll get the days between the 2 dates.
This works because of PHP's string comparison logic. Simply you can check...
if ($startdate < $date) {// do something}
if ($startdate > $date) {// do something}
Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.
If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:
$date = $row->expireDate;
$date->add(new DateInterval('PT24H')); // adds 24 hours
$now = new \DateTime();
if($now < $date) { /* expired after 24 hours */ }
But in your case you could do the comparison just as the following:
$today = new DateTime('Y-m-d');
$date = $row->expireDate;
if($today < $date) { /* do something */ }
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday];
$current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps

Date Variables not working as accepted in php? [duplicate]

How can I compare two dates in PHP?
The date is stored in the database in the following format
2011-10-2
If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?
I tried this,
$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
but it doesn't really work that way. What's another way of doing it?
If all your dates are posterior to the 1st of January of 1970, you could use something like:
$today = date("Y-m-d");
$expire = $row->expireDate; //from database
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { /* do Something */ }
If you are using PHP 5 >= 5.2.0, you could use the DateTime class:
$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);
if ($expire_dt < $today_dt) { /* Do something */ }
Or something along these lines.
in the database the date looks like this 2011-10-2
Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.
Just to compliment the already given answers, see the following example:
$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database
if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) {
//do something;
}
Update:
Or simple use old-school date() function:
if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
//echo not yet expired!
}
I would'nt do this with PHP.
A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types
SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
Here's a way on how to get the difference between two dates in minutes.
// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));
// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;
echo $difference_in_minutes;
You can convert the dates into UNIX timestamps and compare the difference between them in seconds.
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
{
echo "Enter a valid date";
}
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
Here's my spin on how to get the difference in days between two dates with PHP.
Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.
$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";
Found the answer on a blog and it's as simple as:
strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
And you'll get the days between the 2 dates.
This works because of PHP's string comparison logic. Simply you can check...
if ($startdate < $date) {// do something}
if ($startdate > $date) {// do something}
Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.
If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:
$date = $row->expireDate;
$date->add(new DateInterval('PT24H')); // adds 24 hours
$now = new \DateTime();
if($now < $date) { /* expired after 24 hours */ }
But in your case you could do the comparison just as the following:
$today = new DateTime('Y-m-d');
$date = $row->expireDate;
if($today < $date) { /* do something */ }
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday];
$current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps

Compare dates in different years php [duplicate]

How can I compare two dates in PHP?
The date is stored in the database in the following format
2011-10-2
If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?
I tried this,
$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
but it doesn't really work that way. What's another way of doing it?
If all your dates are posterior to the 1st of January of 1970, you could use something like:
$today = date("Y-m-d");
$expire = $row->expireDate; //from database
$today_time = strtotime($today);
$expire_time = strtotime($expire);
if ($expire_time < $today_time) { /* do Something */ }
If you are using PHP 5 >= 5.2.0, you could use the DateTime class:
$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);
if ($expire_dt < $today_dt) { /* Do something */ }
Or something along these lines.
in the database the date looks like this 2011-10-2
Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.
Just to compliment the already given answers, see the following example:
$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database
if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) {
//do something;
}
Update:
Or simple use old-school date() function:
if(date('Y-m-d') < date('Y-m-d', strtotime($expire_date))){
//echo not yet expired!
}
I would'nt do this with PHP.
A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types
SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
$today = date('Y-m-d');//Y-m-d H:i:s
$expireDate = new DateTime($row->expireDate);// From db
$date1=date_create($today);
$date2=date_create($expireDate->format('Y-m-d'));
$diff=date_diff($date1,$date2);
//echo $timeDiff;
if($diff->days >= 30){
echo "Expired.";
}else{
echo "Not expired.";
}
Here's a way on how to get the difference between two dates in minutes.
// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));
// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;
echo $difference_in_minutes;
You can convert the dates into UNIX timestamps and compare the difference between them in seconds.
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
{
echo "Enter a valid date";
}
I had that problem too and I solve it by:
$today = date("Ymd");
$expire = str_replace('-', '', $row->expireDate); //from db
if(($today - $expire) > $NUMBER_OF_DAYS)
{
//do something;
}
Here's my spin on how to get the difference in days between two dates with PHP.
Note the use of '!' in the format to discard the time part of the dates, thanks to info from DateTime createFromFormat without time.
$today = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));
$wanted = DateTime::createFromFormat('!d-m-Y', $row["WANTED_DELIVERY_DATE"]);
$diff = $today->diff($wanted);
$days = $diff->days;
if (($diff->invert) != 0) $days = -1 * $days;
$overdue = (($days < 0) ? true : false);
print "<!-- (".(($days > 0) ? '+' : '').($days).") -->\n";
Found the answer on a blog and it's as simple as:
strtotime(date("Y"."-01-01")) -strtotime($newdate))/86400
And you'll get the days between the 2 dates.
This works because of PHP's string comparison logic. Simply you can check...
if ($startdate < $date) {// do something}
if ($startdate > $date) {// do something}
Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.
If you want a date ($date) to get expired in some interval for example a token expiration date when performing a password reset, here's how you can do:
$date = $row->expireDate;
$date->add(new DateInterval('PT24H')); // adds 24 hours
$now = new \DateTime();
if($now < $date) { /* expired after 24 hours */ }
But in your case you could do the comparison just as the following:
$today = new DateTime('Y-m-d');
$date = $row->expireDate;
if($today < $date) { /* do something */ }
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday];
$current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps

loop array values

Here I access 'date' key values from rows of DB table. And I can echo these values, no problem.
$res = $mysqli->query("SELECT * FROM alfred ORDER BY id ASC");
$row = $res->fetch_all(MYSQLI_ASSOC);
foreach ($row as $key => $value){
$availDate = $value['date'];
echo $availDate.'<br />';
}
This loop above shows all 'date' values from DB, in this case there are 3 dates- "2012-09-25" "2012-09-27" and "2012-09-29".
But then I need to compare each of these 'date' values against values of $date->format('Y-m-d') from the code below and display each date with corresponding "busy" or "available" status into separate <td> of the table. My following version compares only the "last" value of 'date' key - "2012-09-29", but I need to compare each 'date' value from the array above, it means also "2012-09-25" and "2012-09-27". I have tried many versions but still unsuccessful. Any ideas?
$date = new DateTime();
$endDate = new DateTime('+10 day');
for($date->format('Y-m-d'); $date->format('Y-m-d') < $endDate->format('Y-m-d'); $date->modify('+1 day')){
if ($date->format('Y-m-d') == $availDate){
echo '<td>'.$date->format('Y-m-d/D').' busy</td>';
} else {
echo '<td>'.$date->format('Y-m-d/D').' available</td>';
}
}
Here is the result I am getting now:
2012-09-21/Fri available 2012-09-22/Sat available 2012-09-23/Sun available 2012-09-24/Mon available 2012-09-25/Tue available 2012-09-26/Wed available 2012-09-27/Thu available 2012-09-28/Fri available 2012-09-29/Sat busy 2012-09-30/Sun available
But in fact I need to show "busy" status also into <td> of "2012-09-25" and <td> of "2012-09-27" as these also are 'date' values that are existing in $row array. Unfortunately I can not post any images here to show, but I hope my result above gives you the idea.
SOLVED with the help of in_array below:
$aAvailDate = array();
foreach ($row as $key => $value){
$aAvailDate[] = $value['date'];
}
$date = new DateTime();
$endDate = new DateTime('+10 day');
for($date->format('Y-m-d'); $date->format('Y-m-d') < $endDate->format('Y-m-d'); $date->modify('+1 day')){
if (in_array($date->format('Y-m-d'), $aAvailDate)){
echo '<td>'.$date->format('Y-m-d/D').' busy</td>';
} else {
echo '<td>'.$date->format('Y-m-d/D').' available</td>';
}
}
I haven't tested your code, but I think you are running ->format('Y-m-d') unnecessarily here, and this is messing up your logic.
Every time you run that, PHP is turning your object into a string, which you are then comparing against other strings. This won't do anything useful.
Instead, you should be using the features of the DateTime class to compare the objects themselves. The only time you should need to use the format() method is when outputting to the browser, into an SQL query, etc
Although your Question is Unclear but AFAIK
you want to display "Busy" if available date occurs between given date upto 3 Weeks
otherwise display "free"
I would like to suggest you to do this with MySQL (Not tested)
SELECT *,
IF( `DateCol` BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 3 WEEK), 'Busy','Free')
AS status
FROM TableName
Try a while loop instead of a foreach. Also, compare the DateTime objects directly, not the formatted strings.
$date = new DateTime();
$endDate = new DateTime('+3 week');
while( $date < $endDate) {
if ($date->format('Y-m-d') == $availDate){
echo '<td class="busy">busy</td>';
} else {
echo '<td>free</td>';
}
$date->modify("+1 day");
}
Something like this? (If I understand what you're trying to do correctly)
<?php
$avail_dates = array();
$res = $mysqli->query("SELECT DATE_FORMAT(date, '%Y-%m-%d') AS availDate FROM alfred ORDER BY id ASC");
$row = $res->fetch_all(MYSQLI_ASSOC);
foreach ($row as $key => $value){
$avail_dates[] = $value['availDate'];
}
$startDate = date('Y-m-d');
$endDate = date('Y-m-d', strtotime(date("Y-m-d", strtotime($startDate)) . " +3 week"));
?>
<table>
<?php
foreach ($avail_dates as $availDate){
echo "<tr><td>$availDate</td>";
if (($startDate <= $availDate) && ($endDate >= $availDate)){
echo "<td class='busy'>busy</td>";
}else{
echo "<td>free</td>";
}
echo "</tr>";
}
?>
Instead of printing values, I would add them to the array, and then run a loop on that array, comparing the values to the given start and end dates. I also wouldn't fetch all from the table if you nly need a date.
May be like this?
$date = new DateTime();
$endDate = new DateTime('+3 week');
for($date->format('Y-m-d'); $date->format('Y-m-d') < $endDate->format('Y-m-d'); $date->modify('+1 day')){
$tempDate = $date->format('Y-m-d');
if ($tempDate === $availDate){
echo '<td class="busy">busy</td>';
} else {
echo '<td>free</td>';
}
}

Getting the next date of a day in MySQL database (PHP)

I have a series of weekly events in a database along with the day they happen on (in full form, so: 'Monday', 'Tuesday' etc). I've successfully printed the events in a while loop ordered by today, tomorrow, etc, but I'd like to put the date in brackets next to each one.
I thought it might be a case of (mock code):
$today = date("l");
$todays_date = date("j M");
if (day == $today) {
$date = $todays_date;
}
else if (day == $today + 1) {
$date = $todays_date + 1;
}
else if (day == $today + 2) {
$date = $todays_date + 2;
}
etc...
But I'm not so sure. It'd be ideal if I could just have the date in the database, but this seems to go against the grain of what MySQL is about.
Also, I'd like to ideally format the date as: 11 Jun.
EDIT
Presumably it's also got to fit into my while loop somehow:
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array($row[0]);
echo "<option>" . $row[0] . "</option>";
}
}
You can use strtotime?
echo "Today: ".date("j M");
echo "Tomorrow: ".date("j M", strotime("+1 day"));
You can use strtotime:
echo strtotime("+1 day");

Categories