check if new DateTime is today or future in php - php

I need to check if date1 is today or future date and if so its ok
if not (is in the past) its not ok. i see a lot of examples but none of theme is check if date1 is equal today.
my code is:
$today = new DateTime(); // Today
$today->format('Y-m-d'); //2016-10-27
$contractDateBegin = new DateTime($date1); //2016-10-27
if($today->getTimestamp() <= $contractDateBegin->getTimestamp()){
echo 'OK';
}
else{
echo "NOT OK";
}
its work fine if date1 is a future date but if its the same date its echo "NOT OK"
any help?

$today can be defined as just new DateTime("today"), which means today at midnight -- the time part will be automatically zeroed out
$today = new DateTime("today");
$date1 = '2016-10-27';
$contractDateBegin = new DateTime($date1); //2016-10-27
if($today <= $contractDateBegin){
echo 'OK';
}
else{
echo "NOT OK";
}
DEMO

The "Y-m-d format" is perfect also for direct lexicographical comparison of strings and there is no need to convert it to a DateTime object. With PHP7 you could use the famous speceship operator ;)
php -a
Interactive mode enabled
php > $today = '2016-10-27';
php > $tomorrow = '2016-10-28';
php > $today2 = '2016-10-27';
php > echo $today <=> $tomorrow;
-1
php > echo $today <=> $today2;
0
php > echo $tomorrow <=> $today2;
1

getTimestamp() included "H:i:s". So it'll fail when compare the seconds.
In your case, do you want to compare just date('Y-m-d')?
If you just want to use DateTime and compare Timestamp. Please try
$today = new DateTime(); // Today
$contractDateBegin = new DateTime($date1); //2016-10-27
// Set time to 0
$today->setTime(0, 0, 0);
$contractDateBegin->setTime(0, 0, 0);
if($today->getTimestamp() <= $contractDateBegin->getTimestamp()){
echo 'OK';
}
else{
echo "NOT OK";
}

I guess you only want to compare the dates (ignoring the time). This should work:
$today = new DateTime();
$today = $today->format('Y-m-d');
$contractDateBegin = new DateTime($date1);
$contractDateBegin = $contractDateBegin->format('Y-m-d');
if ($today <= $contractDateBegin){
echo 'OK';
} else {
echo "NOT OK";
}

Related

How to get current datetime in order to compare with other date in a specif datetime

I need to compare a datetime field called "last_power" to a specific range time that starts at 7AM every day.
For example:
Day starts at 7AM.
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/14 06:40:40 PM -> true
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/15 11:40:40 AM -> false
I'm stucked when "last_power" is between midnight and 6:59 AM.
NOW() = 2022/12/15 12:40:40 AM || last_power is setting to 2022/12/14 01:40:40 AM -> SHOULD BE true because in my code "2022/12/15 12:40:40 AM" is < 7AM of today, but the result give me a false result.
//set
$current = time();
$new_day = strtotime('today 7:00');
$date_power = strtotime($last_power);
if ($current - $date_power >= (24 * 60 * 60) ||
($date_power < $new_day && $current >= $new_day))
{
echo "true";
//last_result < today 7:00AM -> you award your price
} else {
echo "false";
//last_result > today 7:00AM -> you have already received the price for today
}
The trick is to determine the correct cutoff time or correct date for the cutoff. This is much easier with the DateTime object.
$last_power = 'yesterday 7:00:01';
$current = new DateTime('today 6:59:59'); // demo, for production use: new DateTime('now')
$new_day = new DateTime('today 7:00'); // can be past or future
$date_power = new DateTime($last_power); // you may need to use: (new DateTime())->createFromFormat()
if($current < $new_day){ // prior to 7am
$new_day->modify('-1day'); // adjust the cutoff date
}
// now a simple comparison
if($date_power < $new_day){
echo "true, price is older than " .$new_day->format('Y-m-d, H:i:s');
}else{
echo "false, price is same age or newer than " .$new_day->format('Y-m-d, H:i:s');
}
The above will output the following (today being 2022-12-16):
false, price is newer than 2022-12-15, 07:00:00
Run it live here.
using the DateTime builtin class makes life quite easy here
$power_date = '12/16/2022 02:40:40 PM';
$power_d = (new DateTime())->createFromFormat('m/d/Y H:i:s a', $power_date);
echo 'power_date = ' . $power_d->format('d/m/Y H:i:s');
echo PHP_EOL;
$valid_end = new DateTime('today 07:00:00');
echo 'Valid End Date time = ' . $valid_end->format('d/m/Y H:i:s');
echo PHP_EOL;
$valid_start = new DateTime('yesterday 07:00:00');
echo 'Valid Start Date time = ' . $valid_start->format('d/m/Y H:i:s');
echo PHP_EOL;
if ( $power_d > $valid_start && $power_d < $valid_end) {
echo 'VALID';
} else {
echo 'INVALID';
}

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

how to understand if one date in php is less than another minus one day?

how to understand if one date in php is less than another minus one day? I mean if for example a date is set to "2018/07/03"; how can I understand if a given date is less than "2018/07/02"
date1 : year1/month1/day1
date2: year2/month2/day2
<?php
if ($year1 >= $year2) {
if ($month1 >= $month2) {
if (($day1 - 1) > $day2) {
echo 'you could do something..';
}
}
}
?>
the above code fails if forexample $year2 = 2017 and $month2 = 11.. can anybody help me? thanks a lot..
Here, this should work.
$date_to_check = new DateTime($yesterday);
$today = new DateTime();
$time_diff = $today->diff($date_to_check)->d;
if($time_diff > 1) {
echo "This is greater than one day.";
}else{
echo "This is not greater than one day.";
$date = strtotime("2018/07/01");
$date2 = strtotime("2018/07/02");
if($date > $date2){
print('date is bigger');
// do stuff when date is bigger than date2
} else {
// else ...
print('date2 is bigger');
}
To convert string to date php has function named strtotime().
Compairing date objects is simple.
There is full information about strtotime()
http://php.net/manual/ru/function.strtotime.php
Another way:
$date = new DateTime("2018/07/01");
$date2 = new DateTime("2018/07/02");
if($date->modify("+1day") > $date2){
print('date is bigger');
// do stuff when date is bigger than date2
} else {
// else ...
print('date2 is bigger or equal');
}
Notice modify modifies $date object itself.
Read more here http://php.net/manual/en/class.datetime.php

Comparing DateTime Not Working

I created two datetime objects where $date1 = 09/02/2013 and $date2 = 03/02/2014
When I run the following code:
if ($date2 < $date1)
{
echo "hi";
}
for some reason it echos "hi" although $date2 is clearly greater than $date1. How am i supposed to compare these two dates? Please help!
<?php
$date1 = new DateTime ('2013-12-25');
$date2 = new DateTime ('2014-11-24');
if ($date1 > $date2) {
echo ('date1 is greater than date2');
}
else {
echo ('date2 is greater than date1');
}
use like below with function http://php.net/manual/en/function.strtotime.php
if (strtotime($date2 ) < strtotime($date1))
{
echo "hi";
}
hope this will sure help you.
That could work in JavaScript, but in PHP it will not :P
However, you could calculate an interval between dates.
$interval = $date1->diff($date2);
if ($interval->invert){ //1 if negative and 0 if positive
// $date2 has a bigger time value
} else {
// $date1 has a bigger time value
}

Categories