Get difference between two dates in hours inside foreach loop - php

What i want is to get difference between start and ends dates for user. there are 3 dates for a user which has start date and end dates. and all dates coming from database when i try i am unable to get desired result which is to get differences between dates such as 2 days, 3 days, 4 days from list of dates, and no error is showing.
My Code
<?php
$eid = $_SESSION['eid'];
$sql = "SELECT empid,ToDate,FromDate from tblleaves where empid=:eid";
$query = $dbh->prepare($sql);
$query->bindParam(':eid',$eid,PDO::PARAM_STR);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0) {
foreach($results as $result)
{
$diff = date_diff($result->ToDate, $result->FromDate);
echo $diff->format("%h Hours");
htmlentities($result->FromDate));
}
}
?>
Database:

Is there anything outputted by your echo statement?
As fat as PHP is concerned the value returned by mysql/pdo is a string.
You have at least two options.
From the first example in the php docs for date_diff:
https://www.php.net/manual/en/datetime.diff.php
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Notice that they convert the date string to a date object first.
Then you can use date_diff or
$someDateObj->diff($dateObjTwo)
An alternative that works just as well is to select the date fields as a unix timestamp, then subtract both timestamps and convert the remaining absolute value to time in the format you wish. I may follow up with an example of that later.
edit - answering on my tiny phone so I missed the date format issue

Your date format in database is wrong, you have to fix that first by replacing the / with - eg.str_replace('/', '-', $result->ToDate))
then you have to convert the date to correct format like Y-m-d, after that you can check the difference, here is the solution for you
$to = date('Y-m-d', strtotime(str_replace('/', '-', $result->ToDate)));
$from = date('Y-m-d', strtotime(str_replace('/', '-', $result->FromDate)));
$datediff = strtotime($to) - strtotime($from);
echo abs(round($datediff / (60 * 60 * 24)));
if you want the difference in hours you can try the below code
$hourdiff = abs(round(($datediff)/3600, 1));
I hope this will help you

I ended up with this code this definitely help others.
$eid=$_SESSION['eid'];
$sql = "SELECT empid,ToDate,FromDate from tblleaves where empid=:eid";
$query = $dbh->prepare($sql);
$query->bindParam(':eid',$eid,PDO::PARAM_STR);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0)
{
foreach($results as $result)
{
$to = date('Y-m-d', strtotime(str_replace('/', '-', $result->ToDate)));
$from = date('Y-m-d', strtotime(str_replace('/', '-', $result->FromDate)));
$hours = round(abs(strtotime($from) - strtotime($to))/60/60).'<br>';
$sum+=$hours;
}
echo '<h5>'.$sum.' Hours '.'</h5>';
}
?>

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

Weird result when taking date from mysql

I want to substract 2 dates and take the result in minutes like the code bellow gives me the answer i want.
$to_time = strtotime("2017-03-27 17:31:40");
$from_time = strtotime("2017-03-27 18:32:40");
echo "sunolo1: ".round(abs($to_time - $from_time) / 60,2). " minute";
But when i try to retrieve dynamically date from mysql using php it doesnt work it returns 0. (date in my table is in timestamp)
$d = new DateTime("now", new DateTimeZone("Europe/Athens"));
$dateM = $d->format("Y-m-j H:i:s");
$result = mysqli_prepare($con, "SELECT date FROM mytable WHERE id= ? ");
mysqli_stmt_bind_param($result, 'i', $ids);
mysqli_stmt_execute($result);
mysqli_stmt_bind_result($result, $ddd);
while(mysqli_stmt_fetch($result)){
$sunolo_krathshs = round(abs($ddd - $dateM) / 60,2);
echo "sunoloo: ".$sunolo_krathshs;
}
You need to parse the value of $ddd to a DateTime object, since the easiest way would be to compare DateTime objects.
$date = new DateTime();
$ddd = $date->setTimestamp($ddd);
$sunolo_krathshs = round(abs($ddd - $d) / 60,2);
Please check this.
<?php
$datetime1 = new DateTime("2017-03-27 17:31:40");
$datetime2 = new DateTime("2017-03-27 18:32:40");
$interval = $datetime1->diff($datetime2);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
?>
Use strtotime function while passing the date values for calculation. Something like this:
$sunolo_krathshs = round(abs(strtotime($dateM) - strtotime($ddd)) / 60,2);
Using the DateTime class this can be quite simple
$result = mysqli_prepare($con, "SELECT date FROM mytable WHERE id= ? ");
mysqli_stmt_bind_param($result, 'i', $ids);
mysqli_stmt_execute($result);
mysqli_stmt_bind_result($result, $ddd);
$to_time = new DateTime("now", new DateTimeZone("Europe/Athens"));
while(mysqli_stmt_fetch($result)){
// probably want UTC as date times are stored on the db in UTC
// but you may need to experiment with timezones here
$from_date = DateTime::createFromFormat('Y-m-d H:i:s', $ddd, new DateTimeZone("UTC"));
echo round(abs($to_date->getTimestamp() - $from_date->getTimestamp()) / 60,2). " minute";
}
There is no assigment value operation for variable $ids...

How can I find the percentage of completion?

I'm working on a PHP page that calculates the percentage of completion of a project. For example, if you had a start date of January 1st, 2015, and an end date of March 3rd, 2015, and today was February 2nd, 2015, the project would be estimated to be about 50% done. So far I've attempted using the DateTime class and the date_diff function, but I couldn't divide the two, so I'm back at square one. Obviously I need to take Daylight Saving and leap years into account, so that adds an additional layer of complexity to the matter. Any ideas? Here the current block.
try {
$dbh = new PDO('mysql:host=localhost; dbname=jkaufman_hartmanbaldwin', $username, $password, array(
PDO::MYSQL_ATTR_SSL_KEY => '../php_include/codekaufman_com.key',
PDO::MYSQL_ATTR_SSL_CERT => '../php_include/codekaufman_com.crt',
PDO::MYSQL_ATTR_SSL_CA => '../php_include/codekaufman_com.ca_bundle'
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$projectName = $_GET['project'];
$sth = $dbh->prepare('SELECT start, end FROM projects WHERE name = ?');
$sth->execute([$projectName]);
if($sth->rowCount()) {
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
date_default_timezone_set('America/Los_Angeles');
$date = strtotime($row[0]['start']);
$start = date('m/d/Y', $date);
echo $start;
$date = strtotime($row[0]['end']);
$end = date('m/d/Y', $date);
echo " " . $end;
$today = date('m/d/y');
echo $end - $start;
}
} catch(PDOException $e) {
echo $e->getMessage();
}
With reference to How to Minus two dates in php:
$start = new DateTime($row[0]['start']);
$end = new DateTime($row[0]['end']);
$today = new DateTime();
$total = $start->diff($end);
$current = $start->diff($today);
$completion = $current->days / $total->days;
MySQL has some pretty easy to use functions for this sort of thing, you can just gather the info you need in your query:
SELECT start, end, DATEDIFF(end, start) as total_days, DATEDIFF(end, NOW()) as days_remaining
FROM projects WHERE name = ?
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff
From there you just need to divide days_remaining by total_days to get the percentage. Datediff should take leap years and DST into account.
You can use TIMEDIFF in place of DATEDIFF if you need to be more precise, just make sure to convert the sql timestamps to integers with strtotime.
You may also need to set the timezone:
SET time_zone = 'America/Los_Angeles';
The formula is:
percentage = (date - start) / (end - start) * 100
As a PHP function:
function date_progress($start, $end, $date = null) {
$date = $date ?: time();
return (($date - $start) / ($end - $start)) * 100;
}
Example:
$start = strtotime("January 1st 2015");
$end = strtotime("March 3rd 2015");
$date = strtotime("February 2nd 2015");
$percent = date_progress($start, $end, $date);
// "You are 52.46% there!"
echo 'You are ', round($percent, 2), '% there!';
Get your SQL output in the right format (YYYY-MM-DD) and then shove it into the code below:
<?php
$startDate = date_create('2015-01-01');
$endDate = date_create('2015-01-30');
$currentDate = date_create('2015-01-08');
$totalTime = date_diff($endDate, $startDate);
$elapsedTime = date_diff($currentDate, $startDate);
$totalTimeDays = $totalTime->format("%d");
$elapsedTimeDays = $elapsedTime->format("%d");
echo "Total project time = " . $totalTimeDays . "<br/>";
echo "Elapsed project time = " . $elapsedTimeDays . "<br/>";
echo "Percent of project complete = " . ($elapsedTimeDays / $totalTimeDays) * 100.0;
?>
$start = new DateTime("<YOUR START DATE>"); // example input "2014/06/30"
$end= new DateTime("<YOUR END DATE>");
$now = new DateTime();
$intervalOBJ = $start->diff($end);
$totalDaysOfProject = $intervalOBJ->format('%a');
$intervalOBJ_2 = $now->diff($end);
$daysRemaining = $intervalOBJ_2->format('%a');
$completedPercentage = round(($daysRemaining/$totalDaysOfProject)*100);
echo $completedPercentage . "% of this project has been completed!";
Description: This calculates the percentage of days remaining. interval = $start to $end. Calculated percentage is in relation to $now.

Categories