PHP days difference - php

Hello i'm trying to make a php script that compares the date from one of my database records and todays date, if the difference in days is greater than 3, it will come out to true.
example:
$todays_date = date("Y-m-d"); <-- Todays date
$deal_date = $data["Deal Date"]; <-- Date from database
$interval = date_diff($todays_date, $deal_date); <--Difference
if($interval >= 3)
{
(something)
}
but every time i try this i get an error "date_diff() expects parameter 1 to be DateTime, string given" i know that to use date_diff both arguments have to be datetime, but i'm not sure how to get today's date in date and how to convert the date from the database into datetime.

Try this code:
$date1 = new DateTime('now');
$date2 = new DateTime($data['Deal Date']);
$interval = $date1->diff($date2);
if ($interval->format('%a') >= 3) {
...
}
More examples in PHP date_diff documentation.

CORRECT SYNTAX IS:
<?php
$datetime1 = date_create('now');
$datetime2 = date_create($data["Deal Date"];);
$interval = date_diff($datetime1, $datetime2);
$diff = $interval->format('%a');
if($diff >= 3)
{
(something)
}
?>

Related

Unable to correctly calculate date with "0000-00-00" date in php

I have two date like this
$date1 = "2018-11-07";
$date2 = "2018-11-12";
I want to compare these two date so i could get a range of day between these date. I used DiffDate function. It's looks like below syntax.
$datediff1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
$interval = $datediff2->diff($datediff1);
echo $interval->d; // will return 5
I got the function, but i have problem when one from these two date had a value like "0000-00-00". They started to looks like this.
$date1 = "2018-11-07";
$date2 = "0000-00-00";
$datedif1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
$interval = $datediff2->diff($datediff1);
echo $interval->d; // will return 8
//// If i reverse the date like $datediff1->diff($datediff2);
//// it will return 7 instead
My question is how could i prevent these two dates return 0 when one or all dates have "0000-00-00" value ? I have tried like using if...else....
if($date1 == "0000-00-00" || $date2 == "0000-00-00"){
$interval = "0";
echo $interval;
}else {
$interval = $date2->diff($date1);
$i = $interval->d;
}
Is there any better way to do it rather than using if else statement ?
SEE IT ONLINE HERE
PS : I am using PHP 5.6
You can rely on the fact that the timestamp starts with 1970 so a 0000 year would result a negative timestamp :
$date1 = "2018-11-07";
$date2 = "0000-00-00";
$datedif1 = new DateTime($date1);
$datediff2 = new DateTime($date2);
// check if strtotime returns a valid timestamp and the year is not 0000
$interval = (!strtotime($date1) ||
!strtotime($date2) || strtotime($date1) < 0 ||
strtotime($date2) < 0) ? 0 : $date2->diff($date1);
print_r($interval);
This needs to be refined because it won't work in all cases but it's working in your case.

comparing time in php error

i'm trying to compare the current time against 5 other times as a schedule but it's not working. Dates are fetched from the database here's the code
$now = new DateTime();
$date1 = new DateTime($pRow['date1']);
$date2 = new DateTime($pRow['date2']);
dates in database:
date1: 12:00
date2: 03:25
if($now->format('h:i') >= $date1->format('h:i') && $now->format('h:i') <= $date2->format('h:i')){
echo "date2";
}
else{
echo "no";
}
the result is always no (code edited to be simple and faster to solve the problem)
if($now >= $date5 && $now <= $date5)
wrong data is comparing
When using the h modifier for time you are working with only 1-12 for hours. This means 2pm is just 2 and 11am is 11. Therefore 11 > 2 which breaks your math. Use H instead.
$now = date("H:i",strtotime("now"));
$date1 = date("H:i",strtotime($pRow['date1']));
$date2 = date("H:i",strtotime($pRow['date2']));
$date3 = date("H:i",strtotime($pRow['date3']));
$date4 = date("H:i",strtotime($pRow['date4']));
$date5 = date("H:i",strtotime($pRow['date5']));
Or, better yet, use DateTime which are comparable.
$now = new DateTime();
$date1 = new DateTime($pRow['date1']);
$date2 = new DateTime($pRow['date2']);
$date3 = new DateTime($pRow['date3']);
$date4 = new DateTime($pRow['date4']);
$date5 = new DateTime($pRow['date5']);
This code was already at stackoverflow, try to use it :)
$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
echo "The Time that was entered is behind";
}

how to compare my current time and date with db stored date

here i have stored two dates in db like start date as 2014-07-07 00:00:00 and end date as 2014-07-15 23:59:59. Now how can I check my current date between the two days
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = new DateTime();
$current_time = $now->format('Y-m-d H:i:s');?>
if date1 and date2 are retrieved from db and compare with current date it getting from server if it is between the two days it should be display end time from now.
USE :
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$cdate1 = new DateTime($date1);
$vdate1 = $cdate1->getTimestamp();
$cdate2 = new DateTime($date2);
$vdate2 = $cdate1->getTimestamp();
compare integers ($vdate1 and $vdate2) to each other
Result will be in seconds
Enjoy :)
Just as an Object Oriented style alternative you can create objects as instances of DateTime class, like these:
$date1 = new DateTime('2014-07-07 00:00:00');
$date2 = new DateTime('2014-07-15 23:59:59');
$now = new DateTime();
then, following your logic, you can compare if now is before or after the other dates, like:
var_dump($date2 > $now);
or you can retrieve an instance of DateInterval interface with:
$now_interval_from_date1 = $date1->diff($now);
and then use the format method to know exactly the time/day/etc.. differences, like:
$now_interval_from_date1->format("%R%H hours")
You can find the format params here:
http://www.php.net/manual/it/dateinterval.format.php
If the two dates are exactly in the same format, php allows string comparison.
So you can do the following:
if(strcmp($date1, $current_time) <= 0 and strcmp($date2, $current_time) > 0)
{
// The date is within the limits
}
strcmp is a safer function for string comparison
So, in your case, you could have the following:
<?php
$con=mysqli_connect("localhost","root","","proms"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
date_default_timezone_set("America/New_York");
$current_time =date("h:i:sa");
$result = mysqli_query($con,"SELECT * FROM image");
while($row = mysqli_fetch_array($result)) {
if(strcmp($row['start_date'],$current_time) <= 0 && strcmp($row['end_date'],$current_time) > 0) {
// The date is within the limits
echo "yes";
}
}
?>
'start_date' and 'end_date' should be substituted with your fields' names.
You can do as following to compare current time between two dates
$date1 = '2014-07-07 00:00:00';
$date2 = '2014-07-15 23:59:59';
$now = date('Y-m-d H:i:s');
$date1TimeStamp = strtotime($date1);
$date2TimeStamp = strtotime($date2);
$nowTimeStamp = strtotime($now);
if($date1TimeStamp <= $nowTimeStamp || $date2TimeStamp >= $nowTimeStamp){
$seconds_diff = $date2TimeStamp - $nowTimeStamp;
$days = $seconds_diff/(3600*24);
}else
echo 'No, out';
Edited calculation, now it displays remaining days time from now to end date.
if(strtotime('now') > strtotime($date1) && strtotime('now') < strtotime($date2)) {
$diff = strtotime($date2) - strtotime('now');
}
$diff then contains the difference between the two dates in miliseconds. Just convert miliseconds to days : hours : minutes (Mathematics ?)

Php subtract two dates with different dates returns wrong result

I am trying to subtract two dates using php.
Dateone is stored in the database while datetwo is the current date.
Now, i have this strange scenario:
Dateone is 23-03-13
Date two is 02-04-13
Using different subtraction methods, give different results.
Method One - Returns -21
$sqldate ="SELECT exam_date FROM exam_table";
$fetchdate = mysql_query($sqldate);
$rowdate = mysql_fetch_array($fetchdate);
//Fetch the date stored in the database
$dateone = $rowdate['exam_date'];
//Calculate the current date today
$datetwo =date('d-m-y');
//Calculate the diff between the two dates
$datediff = $datetwo-$dateone;
In this case, $datediff returns -21
Method Two - Returns -7639
$sqldate ="SELECT exam_date FROM exam_table";
$fetchdate = mysql_query($sqldate);
$rowdate = mysql_fetch_array($fetchdate);
//Fetch the date stored in the database
$dateone = $rowdate['exam_date'];
//Calculate the current date
$datetwo =date('d-m-y');
//Calculate the diff between the two dates
$datetime1 = strtotime("$dateone");
$datetime2 = strtotime("$datetwo");
//seconds between the two times
$secs = $datetime2 - $datetime1;
$days = $secs / 86400;
In this scenario, $days returns -7639
Yeah issue is because your date format is not standard to get difference. You need to inform your current format to date & convert it to standard one to get correct difference.
$datetime1 = DateTime::createFromFormat('d-m-Y', '23-03-13'); #In you case it is considering 13-03-2023
$datetime1->format('d-m-YY');
$datetime2 = DateTime::createFromFormat('d-m-Y', '02-04-13'); #In you case it is considering 13-04-2002
$datetime2->format('d-m-YY');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); #output +10 days
CodeViper Demo.
Note: PHP version should be >= 5.3.0.
Why not make it all in the SQL?
"SELECT time_to_sec(datediff(`exam_date`, curdate())) as datedifference FROM exam_table";
and only this in PHP:
fetch_assoc { $datediff = $row['datedifference'];
try this
echo $dateone = '02-04-13';
echo $datetwo = '06-04-13';
echo $datediff = $datetwo-$dateone;
SQL Query will be ideal for this
SELECT DATEDIFF(exam_date,CURDATE()) AS DiffDate FROM exam_table
PHP
$dateone = $rowdate['DiffDate'];
Why not use DateTime::diff? Source : http://php.net/manual/en/datetime.diff.php
$datediff = $datetwo->diff($dateone);
echo $datediff;
This difference will be in epoch. You would need to convert it to your desired format.

How can I check a date from a mysql database `2010-10-18 07:44:53` against a future date using PHP?

I was wondering how would my PHP code look like when I do this?
$end = $now->modify('+1 year');
From #RC answer or, if you prefer, you can use one of this:
$end = $now->setTime(hours, mins, secs);
$end = $now->setDate(year, month, day);
See UNIX_TIMESTAMP() and FROM_UNIXTIME() functions in the MySQL documentation.
See date() function in the PHP manual.
PHP > 5.2:
$start = new DateTime('2010-10-18 07:44:53'); // from MySQL
$now = new DateTime(); // now
$end = $now->modify('+1 year'); // now + 1 yr
if ($start > $end) {
// do something
} else {
// do something else
}
(DateTime doc.)
or use mysql to calculate the difference between your future date and data date.
(mysql date and time functions doc)
$datetime1 =$mysqlReturndate
$datetime2 = new DateTime('Future date');
$interval = $datetime1->diff($datetime2);
use diff() or date_diff()

Categories