Weird result when taking date from mysql - php

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...

Related

Get difference between two dates in hours inside foreach loop

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>';
}
?>

how to get the difference between two dates with timing

I have two dates that are in format Y-m-d
$dateOld = new DateTime("2017-01-10");
$dateNew = new DateTime("2017-01-11");
echo $diff = $dateNew->diff($dateOld)->format("%a");
this is working perfect and giving me exact days left.
But now I have added time and it is in H-M format
Like 23:38 and 17:21 and cannot understand now to get the difference between two dateTime
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");
echo $diff = $dateNew->diff($dateOld)->format("%a");
I want to get the difference even if the value if in floating point. Now to work with date concatenated with time?
Use this:
<?php
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");
$diff = $dateNew->diff($dateOld);
$days = $diff->d;
$hours = $diff->h;
$minutes = $diff->i;
$total_difference = $days + ($hours * 60 + $minutes) / 1440;
echo $total_difference;
Or, without the DateInterval:
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-12 17:21");
$difference_in_seconds = $dateNew->getTimestamp() - $dateOld->getTimestamp();
$total_difference_in_days = $difference_in_seconds / 86400;
echo $total_difference_in_days;
Using ->format("%a") will give you the rounded days.
See http://php.net/manual/en/datetime.diff.php.
$dateNew = '2017-01-11 17:21';
$dateOld = '2017-01-10 23:38';
$dateNew = new DateTime($dateNew);
$dateOld = new DateTime($dateOld);
$diff = $dateNew->diff($dateOld);
echo $diff->format("%H:%I");
Source: http://php.net/manual/en/datetime.diff.php

Getting Total seconds from DateTime php

I want to convert the DateTime after I did a dateDiff to the queried time and the current time into seconds. How do i do that? I currently have it as hh:mm:ss.
$row = mysqli_fetch_array($sql, MYSQL_ASSOC);
$statusTime = $row['date'];
$dteStart = new DateTime($statusTime);
$dteEnd = new DateTime($currentTime);
$dteDiff = $dteStart->diff($dteEnd);
echo $dteDiff->format('%H:%I:%S');
you can use strtotime() function which returns a unix timestamp.
strtotime($dteDiff->format()); should do the trick
Strtotime will give you the time in seconds from 1 of january 1970.
So:
$statustimeUNIX = Strtotime(date("hh:mm:ss",$statusTime));
$currenttimeUNIX = Strtotime(date("hh:mm:ss", $currentTime));
$DiffInSeconds = $currenttimeUNIX - $statustimeUNIX; // or if it's supposed to be the other way around maybe?
There is no need for datetime here unless you need it for something else?
EDIT:
$statustimeUNIX = Strtotime(date("hh:mm:ss",$statusTime));
$currenttimeUNIX = Strtotime(date("hh:mm:ss", $currentTime));
$DiffInSeconds = $currenttimeUNIX - $statustimeUNIX;
If($DiffInSeconds > 300 || ($DiffInSeconds > -86100 && $DiffInSeconds < 0)){
Echo "inactive";
}else{
Echo "active";
}
The easiest way to get seconds between two DateTime objects is to do a simple subtraction:-
$dteStart = new DateTime($statusTime);
$dteEnd = new DateTime($currentTime);
$seconds = $dteEnd->getTimestamp() - $dteStart->getTimestamp();

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.

Number of weeks between two flexible dates - PHP

I have been looking through all the previous questions which similar to this question unfortunately non of them work for me.
I am trying to get the number of weeks between two dates.
$result = mysqli_query($con,"SELECT * FROM `test` WHERE `DateofTest` BETWEEN '" .
$startDate . "' AND '" . $endDate . "' ") or die ("Error: ".mysqli_error($con));
$startDate = $_POST['start'];
$endDate = $POST['end'];
Suppose my start date is 01/12/2014 and end date is 31/12/2014 so 4 weeks.
Here is my code
$startDate ="2014-12-01";
$endDate ="2014-12-31";
$days=($startDate - $endDate);
echo $days;
$weeks=($days / 7);
echo $weeks;
I am getting 0 result for each days and weeks.
Any ideas please.
Thanks
Something like this using the date time object will work
$d1 = new DateTime("2014-12-01");
$d2 = new DateTime("2014-12-31");
$difference_in_days = $d1->diff($d2)->days;
echo "Diff in Weeks = ".$difference_in_days/7;
You can't calculate strings. You need to convert them to dates.
You can do something like:
function get_number_of_weeks($startDate, $endDate) {
// use strtotime and substract the end date from the start date, not the otherway around
$days = strtotime($endDate) - strtotime($startDate);
// devide by seconds / hours and weeks
$weeks = $days / 3600 / 24 / 7;
// floor the amount of weeks.
return floor($weeks);
}
echo get_number_of_weeks("2014-12-01", "2014-12-31");
You cannot compare date strings and expect to get the difference.
You should use the DateTime class to compare two datetime values:
$startDate = new DateTime("2014-12-01");
$endDate = new DateTime("2014-12-31");
$diff = $startDate->diff( $endDate )->format('%d');
$weeks = floor($diff/7);
format method can return a difference in a number of ways like years/months/days/hours/minutes/seconds. More here
Try this..
<?php
$d1 ="2014-12-01";
$d2 ="2014-12-31";
$diffweek = abs(strtotime($d1) - strtotime($d2)) / 604800;
echo round($diffweek); or echo intval($diffweek);
?>

Categories