PHP - Convert this into hours - php

I wanted to convert this into hours:
<?php
( strtotime('12:45:00') - strtotime('11:00:00') ) / 60 (This is for minutes)
?>

You can convert minutes to hour using following function:
<?php
function convertToHoursMins($time, $format = '%02d:%02d') {
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
return sprintf($format, $hours, $minutes);
}
echo convertToHoursMins(250, '%02d hours %02d minutes');
For more info check this post

Although I'm not sure whether I understand you right, here's an example:
<?php
$resultM = ( strtotime('12:45:00') - strtotime('11:00:00') ) / 60; // (This is for minutes)
$resultH = ( strtotime('12:45:00') - strtotime('11:00:00') ) / 3600; // (This is for hours)
$resultH1 = floor(( strtotime('12:45:00') - strtotime('11:00:00') ) / 3600); // (This is for hours)
echo "Minutes=$resultM<br />Hours(float)=$resultH<br />Houres(floor)=$resultH1<br />";
?>

Try this example. Positive and Negative answer will depends on date provided first in date_diff function.
$date1 = date_create("12:45:00");
$date2 = date_create("11:00:00");
$diff=date_diff($date1,$date2);
echo "Difference in Hours\n";
echo $diff->format("%R%H hours")."\n";
echo "Difference in Minutes\n";
echo $diff->format("%R%i minutes");
click here for Working Demo
Another Example
$date2 = new DateTime("12:45:00");
$date1 = new DateTime("11:00:00");
echo "\n\n".$date2->diff($date1)->format("%H hours %i minutes");

Related

Calculate the hours minutes and days of difference between two date and hours

I have a PHP and MySQL code that should calculate the hours minutes and days of difference between two date and hours. It works well, just adding 20 hours and 20 minutes more than normal. And I remove the DATE part and put the date and time manually, it works fine.
I don't understand what happens.
$fecha = $row["fecha"];
$data= $row["hora"];
$start = strtotime("$fecha $hora");
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDate = date("Y-m-d H:i:s", strtotime($currentDate .$currentTime));
$end = strtotime("$currentDate");
$totaltime = ($end - $start) ;
$hours = intval($totaltime / 3600);
$seconds_remain = ($totaltime - ($hours * 3600));
$minutes = intval($seconds_remain / 60);
$seconds = ($seconds_remain - ($minutes * 60));
$statusfichaje= $row["status"];
if ($statusfichaje == Start){echo '<td>Trabajando'.$hours.':'.$minutes.':'.$seconds.' </td>';}else{echo '<td>'. $row["status"] .'</td>';}
Edit
start 2019-12-29 21:27:50 . end 2019-12-31 0:51:50 = 47:51:16
As you can see it calculates badly.
A simple example like this would do the job :
$mydatetime = new DateTime();
$datefromdb = new DateTime('2018-03-05 10:10:00');
$interval = $mydatetime->diff($datefromdb);
$date_count = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $date_count;
This is your code it should work
$fecha = $row["fecha"];
$data= $row["hora"];
$start = strtotime("$fecha $data");
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDate = date("Y-m-d H:i:s", strtotime($currentDate .$currentTime));
$end = strtotime("$currentDate");
$totaltime = ($end - $start) ;
$hours = intval($totaltime / 3600);
$seconds_remain = ($totaltime - ($hours * 3600));
$minutes = intval($seconds_remain / 60);
$seconds = ($seconds_remain - ($minutes * 60));
$statusfichaje= $row["status"];
if ($statusfichaje == $start){echo '<td>Trabajando'.$hours.':'.$minutes.':'.$seconds.' </td>';}else{echo '<td>'. $row["status"] .'</td>';}
problem was in the string.
$data= $row["hora"];
and I use this
$start = strtotime("$fecha $hora");
And don't take the hours and calculate only for days.
Thank you

PHP: Days, hours and minutes left to a certain date?

I'm trying to get remaining Days, hours and minutes to a certain date using php.
However i get a very strange output from my code which looks like this:
-16828 days and -11 hours and -21 minutes and -24 seconds
The future dates are stored in the mysql database in this format:
29/01/2016 7pm
So I went ahead and done this:
$Draw_time = "29/01/2016 7pm";
$date = $Draw_time;
$timestamp = strtotime($date);
$new_date = date('Y-m-d a',$timestamp );
$seconds = strtotime($new_date) - time();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
$seconds %= 3600;
$minutes = floor($seconds / 60);
$seconds %= 60;
echo "$days days and $hours hours and $minutes minutes and $seconds seconds";
But when i run this code, I get the above strange output!
I understand that this could be because of a number reasons but the only thing i could think of is the fact that I am using a in my format?
Could someone please advise on this issue?
Simply use DateTime class like as
$Draw_time = "29/01/2016 7pm";
$date = DateTime::createFromFormat("d/m/Y ha",$Draw_time);
$date2 = new DateTime();
echo $diff = $date2->diff($date)->format("%a days and %H hours and %i minutes and %s seconds");
Try this
<?php
$Draw_time = str_replace('/', '-', "29/01/2016 7pm");
$now = new DateTime();
$futureDate = new DateTime($Draw_time);
$interval = $futureDate->diff($now);
echo $interval->format("%a days %h hours %i minutes %s seconds");
?>
Try this.
$draw_time = "2016/01/29 7pm";
$date_time = explode(" ", $draw_time);// make separate date and time in array
$date = strtotime($date_time[0]); // convert your date(2016/01/29) into php time
$time = strtotime($date_time[1]); // convert your time(7pm) into php time
$date = $date + $time; // make total time to count
$new_Date = $date - (time()); // convert into difference from current time
$day = $new_Date % 86400;
$hrs = $new_Date % 3600;
$min = $new_Date % 60;
echo "Day= ".(date("d",$day));
echo " Hours= ".(date("h",$hrs));
echo " Minutes= ".(date("i",$min));

Php's new DateTime() is not working on my new server

I am trying to calculate the time interval between two Dates. So here is my code
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;
when i try to echo the result it returns an empty result.
This same code worked on my development server and localhost, As soon as i changed to another server it stoped responding.
I checked php.ini for timezone setting, it was good.
I will be thank full for your help
Check your php.ini files inside /etc/php5/apache2/ and /etc/php5/cli/ folders. Both files must have declared the default time zone eg. date.timezone = "America/New_York"
Other way you can have it to work is declaring it inside your code before creating the DateTime object
date_default_timezone_set('America/New_York');
$start_date = new DateTime("$date1");
$end_date = new DateTime("$date2");
$interval = $start_date->diff($end_date);
$days = $interval->d;
$months = $interval->m;
$years = $interval->y;
$hours = $interval->h;
$mins = $interval->i;
$secs = $interval->s;
NOTE: I suggest that you store everything in timestamp in your database rather than in date. And in your display logic, convert it to date, or find how old it is, etc. Read this on Datetime vs timestamp Should I use field 'datetime' or 'timestamp'?
Below,find two functions to find time difference between two timestamps as well as get the age of an old timestamp compared to now.
<?php
echo whatAge(#SOME TIMESTAMP HERE#)
echo getDiff(#TIMESTAMP1, TIMESTAMP2#)
?>
This gives you day hour minute second. Modify the secondsToTime function below for something else.
Use the functions below...
function whatAge($old_time){
$current_time = getdate(time())[0];
$time_diff = $current_time-$old_time;
return secondsToTime($time_diff,'string');
}
function getDiff($time1, $time2){
$time_diff = $time1-$time2;
return secondsToTime($time_diff,'string');
}
function secondsToTime($inputSeconds, $return='array') {
/** https://stackoverflow.com/questions/8273804/convert-seconds-into-days-hours-minutes-and-seconds */
$secondsInAMinute = 60;
$secondsInAnHour = 60 * $secondsInAMinute;
$secondsInADay = 24 * $secondsInAnHour;
// extract days
$days = floor($inputSeconds / $secondsInADay);
// extract hours
$hourSeconds = $inputSeconds % $secondsInADay;
$hours = floor($hourSeconds / $secondsInAnHour);
// extract minutes
$minuteSeconds = $hourSeconds % $secondsInAnHour;
$minutes = floor($minuteSeconds / $secondsInAMinute);
// extract the remaining seconds
$remainingSeconds = $minuteSeconds % $secondsInAMinute;
$seconds = ceil($remainingSeconds);
// return the final array
$obj = array(
'd' => (int) $days,
'h' => (int) $hours,
'm' => (int) $minutes,
's' => (int) $seconds,
);
$str = function($d,$h,$m,$s){
if($d>0){
return "$d d, $h h $m m";
}else{
return "$h h $m m";
}
};
switch ($return){
case 'array' : return $obj; break;
case 'string' : return $str($obj['d'],$obj['h'],$obj['m'],$obj['s']); break;
}
}
Simple Way
Try this:
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
read more [php DateTime::diff manual][1]

Add 15 minutes to current time and snap to 15 minute intervals

I need to add 15 minutes to the current time.
For eg : now is 20:48 , need to add 15 minutes, so now it will be 21:03, but i need to set 21:15 ,that is , it should be in multiples of15,30,45,00.
Help help/guidance would be of good help.
<?php
$current_date_time = date('d/m/Y H:i:s');
$current_date = date("d/m/Y H:i", strtotime($current_date_time."+15 minutes"));
echo $current_date;exit;
Here's a simple example
//what time is it?
$t=time();
//how long is our interval?
$interval=15*60;
//we can calculate when the last interval started by subtracting $t % $interval
$last = $t - $t % $interval;
//so now we know when the next interval will start...
$next = $last + $interval;
echo "Next interval at ".strftime('%H:%M:%S', $next)."\n";
You look like you might want to add 2*$interval to the last interval, but you should be able to adapt this to suit you.
Just to correct my post:
$time = time();
$last_time = ($time - ($time % (15 * 60)));
$in15mins = $last_time+ (15 * 60);
echo 'Now: '. date('Y-m-d H:i') ."\n";
echo 'in 15 mins: '. date('Y-m-d H:i', $in15mins) ."\n";
I think it is quite self explaining. Optimize it, use it.
$current_date_time = date('d/m/Y H:i:s');
echo $current_date_time."<br>";
$current_date = date("d/m/Y H:i", strtotime($current_date_time."+15 minutes"));
echo $current_date."<br>";
$minutes = date("i",strtotime($current_date));
$min = '';
if($minutes > 0 && $minutes <15){
$min = 15 - $minutes;
} else if($minutes > 15 && $minutes <30){
$min = 30 - $minutes;
} else if($minutes > 30 && $minutes <45){
$min = 45 - $minutes;
} else {
$min = 59 - $minutes;
$min++;
}
$newdate = date("d/m/Y H:i", strtotime($current_date."+".$min." minutes"));
echo $newdate;
Use the above code. this is working for me.
$currentTimeStamp=strtotime('now');
$nextInterval=date("Y-m-d H:i", strtotime("+15 minutes", $currentTimeStamp));
dump($nextInterval);

how to calculate hours,minutes and seconds from total minutes in php?

I am developing one website in php.
I need to add jobs to the sql server 2008 database.
I am taking job duration in minutes and i want to convert it in to H:i:s format.
I am using this code :
$hours = (int)($duration / 60);
$minutes = $duration - ($hours * 60);
$time = $hours.":".$minutes;
It works fine with int duration 30,60,100,120 etc.
but if duration is 1.33 or 5.40 than the output should be 00:01:30 or 00:05:40 respectively.
How can i do this ?
try this
<?php
$duration = "1.33";
$hours = (int)($duration / 60);
$minutes = $duration - ($hours * 60);
date_default_timezone_set('UTC');
$date = new DateTime($hours.":".$minutes);
echo $date->format('H:i:s');
?>
output
00:01:33
Use the DateInterval class if you're running PHP > 5.3.0:
$interval = new DateInterval('100 minutes');
$interval->format('%H:%I:%S'); // prep for MySQL database.
As you are taking minutes, this code is working perfectly
$valueInMinutes = 135;
echo intval($valueInMinutes / 60);
echo " h ";
echo intval($valueInMinutes % 60);
and will output
2 h 15
If you have to manage the days, just change a little bit the code to:
$value = 1505;
echo intval($value / 1440);
echo " day(s) ";
echo intval(($value % 1440) / 60);
echo " h ";
echo intval($value % 60);
will output
1 day(s) 1 h 5
You can do with php date function :
$hours = (int)($duration / 60);
$minutes = $duration - ($hours * 60);
$time = date("H:i:s", strtotime($hours.":".$minutes));
echo $time;
More info on date can be found here http://php.net/manual/en/function.date.php
Hope this helps :)
Try this way
$time = 5.40;
$newtime = floatval($time);
echo number_format($newtime,2,':',null);
Try this
echo $time = date("H:i:s", strtotime($hours)) . ":" . date("H:i:s", strtotime($minutes));
Output
01:33:00 : 05:40:00

Categories