I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:
8:30 to 10:00 would be 1:30
A solution might be to use strtotime to convert your dates/times to timestamps :
$first_str = '8:30';
$first_ts = strtotime($first_str);
$second_str = '10:00';
$second_ts = strtotime($second_str);
And, then, do the difference :
$difference_seconds = abs($second_ts - $first_ts);
And get the result in minutes or hours :
$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);
You'll get :
int 90
float 1.5
What you now have to find out is how to display that ;-)
(edit after thinking a bit more)
A possibility to display the difference might be using the date function ; something like this should do :
date_default_timezone_set('UTC');
$date = date('H:i', $difference_seconds);
var_dump($date);
And I'm getting :
string '01:30' (length=5)
Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...
You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.
Use php timestamp for the job :
echo date("H:i:s", ($end_timestamp - $start_timestamp));
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");
The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode(':', $time1);
list($h2,$m2) = explode(':', $time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
echo $time_diff;
Related
Suppose I have a time string '9:30' which I want to convert to timestamp.
What I do right now is extracting it and manually calculate the timestamp.
list($hour, $minute) = explode(':', '9:30');
$timestamp = $hour * 3600 + $minute * 60;
I'm wondering whether there is a smart way using Carbon or DateTime object.
use strtotime()
manual
$time = '9:30';
$timestamp = strtotime($time);
echo date('H:i',$timestamp);
I don't think you'll be able to get a timestamp from only hour or minute, as timestamp is number of seconds from 00:00:00 Thursday 1 January 1970 (check wikipedia link for more details). So without the date part you can't have a timestamp. Could you please explain how you're planning to use this?
If you're planning to calculate a different timestamp from a given datetime, then you can just do it differently. Say you're planning to get the timestamp 1 day or 24 hours after given time, then you can do it like this (non object oriented way):
$givenTimestamp = strtotime('17-06-2018 09:30:00');
$dayInSeconds = 24*60*60;
$calculatedTimeStamp = $givenTimestamp + $dayInSeconds;
If you're just trying to get how many seconds has been passed for the time section of the timestamp (like 9:30 in your example for a given day), then you can just do it like this:
list($hour, $minute) = explode(':', date ('H:i', strtotime('2018-06-16 09:30:00')));
$secondsSinceStartOfDay = intval($hour)*60*60 + intval($minute) * 60;
You may get the same result without using the intval on $hour and $minute, but it would be better to use intval on them to avoid possible issues in some cases.
Update with Carbon
From Carbon documentation, it seems like you still need the date part to generate the timestamp. So if you have your $date like this '2018-06-16' and $time like this '09:30', then you can recreate your datetime like this:
$dateTimeString = $date .' '. $time .':00';
$carbonDateTime = Carbon::parse($dateTimeString);
// $carbonDateTime will now have your date time reference
// you can now get the timestamp like this
echo $carbonDateTime->timestamp;
Im trying to get the difference between 2 differente dates in minutes, but is not outputting correctly.
Ex:
$then = "2017-01-23 18:21:24";
//Convert it into a timestamp.
$then = strtotime($then);
//Get the current timestamp.
$now = time();
//Calculate the difference.
$difference = $now - $then;
//Convert seconds into minutes.
$minutes = floor($difference / 60);
echo $minutes;
Is outputting 611 minutes, and is wrong since from "2017-01-23 18:21:24" to "2017-01-24 12:36:24" it past much more than 611 minutes. Is my code incorrect?
Try to set your default timezone
date_default_timezone_set('Europe/Copenhagen');
Ofc change Europe/Copenhagen for the one that suits your needs.
If you are using or able to use PHP 5.3.x or later, you can use its DateTime object functionality:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
You can play with the format in a variety of ways, and once you have dates in DateTime objects, you can take advantage of a lot of different functionality, for example comparison via normal operators. See the manual for more: http://us3.php.net/manual/en/datetime.diff.php
I've checked your code it works perfectly So if have any doubt see your result
But you got wrong, so to ignore this set your timezone.
I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));
So what I am trying to do is add two strings together in the form of military time. Here is the example.
Time1 = "01:00";
Time2 = "04:30";
Adding the two together would produce "05:30". This seems incredibly simple, but it has been a long long day for a new learner. Any help would be greatly appreciated.
You can do something like this in PHP 5.3:
$d = new DateTime("01:00");
$f = $d->add(new DateInterval("PT04H30M"));
echo $f->format("H:i"); //outputs 05:30
Converting 04:30 to PT04H30M should be trivial. Note that whether this is actually what you want depends on what you mean by "04:30". This code may or may not sum 4*60+30 minutes to the actual time.
If you mean "4 hours and 30 minutes on the clock" this is always correct. However, if you mean "4*60+30 minutes", it depends on the day and timezone. Example:
$d = new DateTime("2010-03-28 01:00 Europe/Lisbon");
$f = $d->setTimestamp($d->getTimestamp() + (4*60+30)*60);
echo $f->format("H:i"); //outputs 06:30 due to DST
An alternate implementation of the last case (assuming current day and default timezone) for PHP 5.2 is
echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));
For the first case, we must do:
date_default_timezone_set("UTC");
echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));
I have an array of times I want to print out. I want the times that have passed lets say 12:00 clock to be 'greyed out'.
$theTime = '12:00';
if($theTime >= $time[$i])
{....}
02:30
03:50
03:20
04:50
05:45
19:45
20:00
20:50
20:55
21:25
21:30
22:00
22:45
23:55
00:50
00:55
Im doing a simple compare 12:00 a clock to each value.
The problem occurs when you change the time to after midnight for example 00:15. How can I calculate and print the list in order, when time has passed midnight?
if you pass midnight, more than one day is involved. this means that you have to include the information of day! what day is it? so in order to achieve what you want you should list/store more than just the time! if you store a datetime value, you will have no problems calculating time differences, since php will know in what order to put the times according to the day information.
for that look at the php datetime functions.
they will also help you to calculate differences!
Use unix timestamps. create a unix time stamp for midnight, and then compare all of the others to that. Then format it as a time when you print it out.
(A while since I used PHP, so can't remember quite how to do it, but should be simple. I know I have done something similar before. Take a look at http://php.net/time, http://php.net/manual/en/function.mktime.php and http://php.net/manual/en/function.date.php. Should be simple enough =)
As Svish said, you should use real timestamps, and you should also check the date change... here the, I think, more quick and easy way to know difference between 2 time (and date) :
<?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
?>
note the $date1 and $date2 have to be in mktime format, as :
int mktime ([ int $hour=date("H") [, int $minute=date("i") [, int $second=date("s") [, int $month=date("n") [, int $day=date("j") [, int $year=date("Y") [, int $is_dst=-1 ]]]]]]] )
I solved this problem as follows. It is not the best solution but at least it works:
$before_midnight = strtotime("23:59:59");
$before_midnight++; // this makes exact midnight
$start = strtotime("21:00");
$target = strtotime("03:00");
$after_midnight = strtotime("00:00");
for($i=$start; $i<$before_midnight; $i += 3600)
echo date("H:i", $i). "<br>";
for($i=$after_midnight; $i<=$target; $i += 3600)
echo date("H:i", $i). "<br>";
You have a string ('12:00') and are trying to compare it like a number.
http://us3.php.net/manual/en/language.operators.comparison.php
Like Svish and Paul said, you need to use integer timestamps.
$now = time(); // Get the current timestamp
$timestamps= array(strtotime('midnight'),
strtotime('07:45'),
...
);
foreach ( $timestampsas $time ) {
if ( $time >= $now ) {
// $time is now or in the future
} else {
// $time is in the past
}
}
You can format the timestamps with the date function.
Re. Svish's suggestion - strtotime() is handy for easily creating Unix timestamps relative to the current time, or any arbitrary time.
e.g. strtotime('midnight') will give you the unix timestamp for the most recent midnight.