Add specific hours in a specific time in php [duplicate] - php

This question already has answers here:
Add time in PHP
(4 answers)
Closed 5 years ago.
Following is code that helps in adding specific hours in present time
date('H:i', strtotime('+1 hours'));
How should i add hours if the time and hours are dynamic. E.g I wish to add 2 hours to time 08:00, but these both things are saved in variables
$hours = "2";
$day_time = "08:00";
I tried the following but didn't work
$new_time = date($day_time, strtotime('+$hours hours'));
can anyone please tell how it can be done

try this
echo date("H:i", strtotime("+{$hours}hour ".$day_time));

Try this
$h = 2 ;
$time="08:00";
$time = date('H:i', strtotime($time.'+'.$h.' hour'));
echo $time;

Try below code,
<?php
$hours = "2";
$day_time = "08:00";
$new_time = date('H:i',strtotime($day_time.'+ '.$hours.' hour'));
echo $new_time;
?>
Output : 10:00

Using datetime would be better to avoid
"A non well formed numeric value encountered"
$date = new DateTime($day_time);
$date->modify("+".$hours." hours");
echo $date->format("H:i");

Try like this,
$hours = 2;
$day_time = "08:00";
$new_time = date('H:i',strtotime($day_time."+$hours hours"));

That's because you are using a variable inside single quotes. There are some ways to fix this:
//awful and you should avoid it
//(hard to read, unsafe use of direct variables inside strings):
$new_time = date($day_time, strtotime("+$hours hours"));
or
//still awful and you should avoid it too:
$new_time = date($day_time, strtotime('+{$hours} hours'));
or
//a little better, but still unsafe:
$new_time = date($day_time, strtotime('+' . $hours . ' hours'));
or
//better, safe because it only adds numeric values to the hours:
$new_time = date($day_time, strtotime(sprintf('+%d hours', $hours)));
or
//the ideal solution, safer to use and more professional:
$dateObj = new DateTime();
$dateObj->modify(sprintf('+%d hours', $hours));
$new_time = $dateObj->format("H:i");
That's the beauty and the curse of PHP, you can always do things in more than one way.

Related

PHP : Not getting correct date difference

I am trying to get difference of two dates to count the duration of time.
This is my code:
<?php
$start_time = '2016-11-02 14:15:02';
$end_time= '2016-11-02 14:17:02';
$diff= strtotime($end_time) - strtotime($start_time);
$duration = date("H:i:s", $diff);
?>
So it is showing 05:32:00, but the actual result should be 00:02:00. I noticed that in result 05:30:00 added. I am not getting solution of it.
Use gmdate instead of date. It returns formated date string.
$duration = gmdate("H:i:s", $diff);
You need to set the defualt time_zone. I think you are using Indian time-zone . Thats why it is detting 5.30 hours more. Please see the below code
date_default_timezone_set("GMT");
$start_time = '2016-11-02 14:15:02';
$end_time= '2016-11-02 14:17:02';
$diff= strtotime($end_time) - strtotime($start_time);
$duration = date("H:i:s", $diff);
echo $duration;
You could use the DateTime Class to get the difference:
$d_start = new \DateTime('2016-11-02 14:15:02');
$d_now = new \DateTime('2016-11-02 14:17:02');
$interval = $d_start->diff($d_now);
Interval is an object which holds the difference in days, hours, minutes as public attribute (http://php.net/manual/de/class.dateinterval.php)
EDIT:
I just checked your code with some debug infos and it seems to work out of the box:
PHP File
$start_unix = strtotime($start_time);
$end_unix = strtotime($end_time);
var_dump($start_unix, $end_unix);
$diff = $end_unix - $start_unix;
var_dump($diff);
$duration = date("H:i:s", $diff);
var_dump($duration);
Console Output
php -f test.php
/tmp/test.php:9:
int(1478096102)
/tmp/test.php:9:
int(1478096222)
/tmp/test.php:12:
int(120)
/tmp/test.php:15:
string(8) "00:02:00"

How to find time different with php

I am trying to find time differences between two times. This is the code I have:
$ddtcounter1="2014-03-06 20:20:30";
$ddtcounter2="2014-03-07 21:20:30";
$today = new DateTime($ddtcounter2);
$pastDate = $today->diff(new DateTime($ddtcounter1));
$total= $pastDate->h . ".";
$total2=$total.$pastDate->i;
echo $total2; //echo the time difference in hour.minutes form (Exmple:2.1)
How can I find the time differences? I have read few guides and tutorials and they didn't help. I read a lot of answers but they didn't work for me...
EDIT:
Example (For who didn't understand the question):
First time: 2014-03-06 20:30:30
second is: 2014-03-07 19:30:30
The time difference will be 23.0 (23 hours), because it happened 1 day earlier!
This should work:
$ddtcounter1="2014-03-06 20:15:30";
$ddtcounter2="2014-03-07 21:20:30";
$date1 = new DateTime($ddtcounter1);
$date2 = new DateTime($ddtcounter2);
$diff = $date1->diff($date2);
$hours = $diff->d * 24;
$hours += $diff->h;
echo $hours;
echo $diff->i; // Minutes
echo sprintf('%s.%s', $hours, $diff->i); // Hours.Minutes

Date is not formatting time correctly PHP

Hello I try to take the difference between two dates and display it.
My problem is that the time difference I get is not the correct one.
This is my code:
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
echo date('H:i', $diffTime);
The result I get is:
02:05
The currect time should be this:
00:05
My guess that the date somehow takes timezone or something like this but Im not sure.
Thanks.
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
So what you're actually doing here is generating two UNIX timestamps (numbers) and then subtracting them. then you're passing the resulting number as if it were still a timestamp to date().
essentially $diffTime is the number of seconds between your two times. you could divide by 60 to get minutes, and so on and so forth, but PHPs DateTime objects are much better.
From the PHP docs:
http://pl1.php.net/strtotime
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
try this
<?php
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
echo round(abs($time1 - $time2) / 60,2). " minute"
?>
Below is the solution of date time in years,days.hours,minutes and seconds.
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
$y = ($diffTime/(60*60*24*365));
$d = ($diffTime/(60*60*24))%365;
$h = ($diffTime/(60*60))%24;
$m = ($diffTime/60)%60;
$s = ($diffTime)%60;
echo "Minutes - " .$m;
echo "<br/>";

find the total hours in PHP by using two date [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP:find day difference between two date(“YmdHis”) reture
I have two dates
$departure_Dtae=2012-07-25T07:30:00
$arrival_date =2012-07-25T10:25:00
T means Time i.e. in 2012-07-25T10:25:00 date is 2012-07-25 and the time is 10:25:00 (hr: mts: s)
I need to find out the total hrs between these two times
I.e. in this case the total hour is 2 hr and 55 minutes
But I don't know how I calculate this in PHP
Does anyone know this?
If using PHP Version 5.3+ then you can use DateTime::diff():
<?php
function getDiff($strStart, $strEnd) {
$start = DateTime::createFromFormat("Y-m-d G:i:s", $strStart);
$end = DateTime::createFromFormat("Y-m-d G:i:s", $strEnd);
return $start->diff($end)->format('%hhrs %imins and %sseconds ');
}
var_dump(getDiff('2012-07-25 07:30:00', '2012-07-25 10:25:00'));
its simple
$departure_Dtae="2012-07-25T07:30:00";
$arrival_date ="2012-07-25T10:25:00";
$departure_Dtae= str_replace("T", " ", $departure_Dtae);
$arrival_date= str_replace("T", " ", $arrival_date);
$diff= (strtotime($arrival_date)-strtotime($departure_Dtae));
echo date("h",$diff);
Try this :
$end_time = "2008-09-05 20:59:13";
$start_time = "2008-09-05 19:00:16";
$end = date("h:i:s",strtotime($end_time));
$start = date("h:i:s",strtotime($start_time));
$diff = strtotime($end) - strtotime($start);
//convert to min and sec
$convert_min = $diff/60;
$convert_sec = $diff % 60;//seconds
//convert to hours and min
$convert_hr = floor($convert_min/60);//hours
$remainder = floor($convert_min % 60);//minutes
$total_visit = $convert_hr.":".$remainder;
You can use the DateTime object in php, which has loads of methods for manipulating dates.
DateTime::createFromFormat http://www.php.net/manual/en/datetime.createfromformat.php and DateTime::diff http://www.php.net/manual/en/datetime.diff.php would be the functions you would need to perform this task.
$date1 = DateTime::createFromFormat('j-M-Y H:i', '15-Feb-2009 12:45');
$date2 = DateTime::createFromFormat('j-M-Y H:i', '15-Feb-2009 13:45');
$interval = $date1->diff($date2);
echo $interval->format('H:i');
strtotime(date($arrival_date)) - strtotime(date($departure_date));
Will give you the time diff in secounds, then you can manipulate that as you wish.

Date problem in PHP

I have a piece of PHP that is trying to do this:
1) given a string like "h m s" (where h=hr, m=min, s=sec)
2) Add the time from 1) to time()
3) format the result to look like "y-mth-d-h-min-s"
So say the time is now 01-01-2011 1am, I want it to add "10 0 0", which should give me 01-01-2011 11am, but for some reason at the moment, it does seem to add the string, but it's not accurate.
This is the code I'm using:
$values_arr['regx_expdate'] = date("Y-m-d H:i:s", time()+$values_arr['regx_expdate']);
where $values_arr['regx_expdate'] is the string in the format "h m s", eg. "10 0 0".
The main question is how would time() know if "10 0 0" is actually 10hrs 0min 0min, and not 10days 0hr 0min??
It does not.
It will cast it to int, interpret it as seconds and add it to the result of time().
Some code that could do as you describe would be:
list ($h,$m,$s) = explode(' ', $values_arr['regx_expdate'], 3);
$difference = 60*60*$h + 60*$m + $s;
$values_arr['regx_expdate'] = date("Y-m-d H:i:s", time()+$difference);
Easiest method I can think of is to extract each token from $values_arr['regx_expdate'], add up the seconds and simple add it to time().
For example
if (preg_match('/^(\d{1,2}) (\d{1,2}) (\d{1,2})$/', $values_arr['regx_expdate'], $units)) {
$seconds = $units[3] + ($units[2] * 60) + ($units[1] * 3600);
$newTimestamp = time() + $seconds;
}
After parsing your input string into Hours Minutes and Seconds, it might be worth reorganizing said array of values into a string that PHP's strtotime can process.
This little function may help, you may customize it to suit your purpose:
function AddingDaysFromNow($number_of_days)
{
$today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
// today is now time return in seconds
$addingTime = $today + (86400 * $number_of_days);
// adding to advance it
//choice a date form at here
return date("Y-m-d", $addingTime);
}
//use it as
$expireDate = AddingDaysFromNow(2); // assume the 2 is advance to 2 days ahead
// return the day in future
Good luck!
To handle and convert dates in php you should first force everything into unixtimestamp and then you give it the structure you want
$date = date("THE-DATE-FORMAT-YOU-WANT", "THE-DATE-YOU-WOULD-LIKE-TO-CONVERT-IN-SECONDS");
//For example.
$new_date = date("Y-m-d H:i:s", strtotime($old_date));
$now = date("Y-m-d H:i:s", time());

Categories