How to add different timestamp - php

I'm having a problem adding two(2) timestamp for example:
00:30:00
00:45:31
========
01:15:31
I can't figure it out how to do it using laravel with carbon...

You can't add time like they are integer. One of the way is to convert it to another format and then add it. After adding them, convert it back to time type.
For example, try this:
$time1 = "00:30:00";
$time2 = "00:45:31";
$secs = strtotime($time2) - strtotime("00:00:00");
$result = date("H:i:s", strtotime($time1) + $secs);
dd($result); // "01:15:31"

My practice is to make TimeHelper class where I declare all my static methods that are related with calculations of time.
So basically I would make static function like this in TimeHelper class:
public static function addTwoTimes($time1 = "00:00:00", $time2 = "00:00:00"){
$time2_arr = [];
$time1 = $time1;
$time2_arr = explode(":", $time2);
//Hour
if(isset($time2_arr[0]) && $time2_arr[0] != ""){
$time1 = $time1." +".$time2_arr[0]." hours";
$time1 = date("H:i:s", strtotime($time1));
}
//Minutes
if(isset($time2_arr[1]) && $time2_arr[1] != ""){
$time1 = $time1." +".$time2_arr[1]." minutes";
$time1 = date("H:i:s", strtotime($time1));
}
//Seconds
if(isset($time2_arr[2]) && $time2_arr[2] != ""){
$time1 = $time1." +".$time2_arr[2]." seconds";
$time1 = date("H:i:s", strtotime($time1));
}
return date("H:i:s", strtotime($time1));
}
So wherever you need to sum two times just call TimeHelper::addTwoTimes(arg1, arg2);
I took example function from user Cha from this topic: PHP add up two time variables

This how you can achieve adding two times with a Carbon date. The explanation is shown in inline comments
$time1 = '00:30:00';
$time2 = '00:45:31';
// Use the first time to crate a new Carbon date
$baseDate = Carbon::parse($time1);
// Deconstruct the second time into hours, minutes and seconds
list($addHour, $addMinutes, $addSeconds) = explode(':', $time2);
// Add the hours, minutes and seconds to the Carbon object
$baseDate->addHours($addHour)->addMinutes($addMinutes)->addSeconds($addSeconds);
// Print the result: 00:30:00 + 00:45:31 = 01:15:31
echo "{$time1} + {$time2} = " . $baseDate->toTimeString();

You can use CarbonInterval class from Carbon library:
$durations = [
'00:30:00',
'00:45:31',
];
function getDuration($string)
{
[$hours, $minutes, $seconds] = explode(':', $string);
return CarbonInterval::hours($hours)->minutes($minutes)->seconds($seconds);
}
$total = getDuration(array_shift($durations));
foreach ($durations as $duration) {
$total->add(getDuration($duration));
}
echo $total->cascade()->format('%h:%i:%s'); // 1:15:31

Related

How to set fix time variables in php?

I want to set a fix time variables in php for my if and else condition.
For example:
$startTime = '08:00:00';
$endTime = '16:00:00';
$totalhrs = $endTime - $startTime;
echo $totalhrs;
Anyone know how to declare the time in PHP?
Thanks for the help
$startTime = strtotime('08:00:00');
$endTime = strtotime('16:00:00');
$totalhrs = ($endTime - $startTime) / 3600;
echo $totalhrs;
you can use datetime object for this case
$startTime = new DateTime('08:00:00');
$endTime = new DateTime('16:00:00');
$totalhrs = $startTime->diff($endTime)->h;
You can try the below function to check timestamps. If you don't pass it a second parameter, it will evaluate if the first time has passed the CURRENT time, otherwise it will compare the first time against the second.
Function timeHasPassed($Time, $Time2 = 0) {
If ($Time2 != 0) {
$Now = new DateTime($Time2);
} Else {
$Now = new DateTime();
}
$Then = new DateTime($Time);
If ($Now > $Then) {
Return TRUE;
} Else {
Return FALSE;
/*
You can also use the below code to print out how long is left until the timestamp has passed. Keep in mind, this will return TRUE if tested as a boolean so maybe consider returning a different datatype instead of TRUE if you decide to go this route.
$Time = new DateTime($Time);
$Now = new DateTime();
$Remainder = $Time->diff($Now);
$Remainder = $Remainder->format("%h hours, %i minutes, and %s seconds!");
return $Remainder;
*/
}
}

How to subtract DATE by day

in my Controller
$ldate = date('Y-m-d ');
$b = DB::table('warehouse_products_sell')
->select([
'warehouse_products_sell.dueto_date'
])
->get();
my output
$b->dueto_date = 2017-10-26
$ldate = 2017-10-07
i want to check
if ($b->dueto_date - $ldate < 5 ){
alert('hi')
}
NOTE : 5 ( day )
not sure how to do .
Laravel uses Carbon library , so you may easily rely on it's cool API,
here is a quick example :
use Carbon\Carbon;
$dt1 = Carbon::createFromFormat('Y-m-d', $b->dueto_date);
$dt2 = Carbon::createFromFormat('Y-m-d', $ldate);
$diff = $dt1->diffInDays($dt2);
if ($diff < 5) {
echo "hi";
}
$DueDate = new DateTime($b->dueto_date); // Due Date
$ldate = new DateTime('Y-m-d') // Your date
$interval = $DueDate->diff($ldate);
if($interval->d < 5){
echo '<script>alert("less than 5 days remaining")</script>';
}
Do it like below:
$days = floor((strtotime($b->dueto_date)- strtotime($your_date))/ (60 * 60 * 24));
if ($days < 5 ){
echo "less than 5 days remaining"; //it's php not jQuery
}else{
echo "$days days remaining";
}
Sample example: https://eval.in/875753

php carbon check if now is between two times (10pm-8am)

$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
How can I check if the time of $now is within the timerange?
There are several ways to achieve that by using Carbon. One of the easiest ways is using createFromTimeString and between methods:
$now = Carbon::now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00')->addDay();
if ($now->between($start, $end)) {
// ¯\_(ツ)_/¯
}
Try this:
$time = Carbon::now();
$morning = Carbon::create($time->year, $time->month, $time->day, 8, 0, 0); //set time to 08:00
$evening = Carbon::create($time->year, $time->month, $time->day, 18, 0, 0); //set time to 18:00
if($time->between($morning, $evening, true)) {
//current time is between morning and evening
} else {
//current time is earlier than morning or later than evening
}
The true in $time->between($morning, $evening, true) checks whether the $time is between and including $morning and $evening. If you write false instead it checks just if it is between the two times but not including.
Actually, you could leave true away because it is set by default and not needed.
Check here for more information on how to compare dates and times with Carbon.
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$time = $now->format('H:i:s');
if ($time >= $start && $time <= $end) {
...
}
Should do it, but doesn't take date into consideration
You can reverse check algorithm.
<?php
$pushChannel = "general";
$now = Carbon::now();
$start = Carbon::createFromTime(8, 0);
$end = Carbon::createFromTime(22, 0);
if (!$now->between($start, $end)) {
$pushChannel = "silent";
$restrictStartTime = Carbon::createFromTime(22, 0, 0); //carbon inbuild function which will create todays date with the given time
$restrictEndTime = Carbon::createFromTime(8, 0, 0)->addDays(1); //this will create tomorrows date with the given time
$now = Carbon::now();
if($now->gt($restrictStartTime) && $now->lt($restrictEndTime)) {
.....
}
Please Try below code,
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$nowTime = $now->hour.':'.$now->minute.':'.$now->second;
if(strtotime($nowTime) > strtotime($start) && strtotime($nowTime) < strtotime($end) ) {
echo 'YES';
} else {
echo 'NO';
}
What Chris is trying to point out is if the endtime crosses over midnight then you must account for that.
This is not the cleanest way to do it but here is a method that seems to work.
private function isNowBetweenTimes($timezone, $startDateTime, $endDateTime) {
$curTimeLocal = Carbon::now($timezone);
$startTime = $curTimeLocal->copy();
$startTime->hour = $startDateTime->hour;
$startTime->minute = $startDateTime->minute;
$endTime = $curTimeLocal->copy();
$endTime->hour = $endDateTime->hour;
$endTime->minute = $endDateTime->minute;
if ($endTime->lessThan($startTime))
$endTime->addDay();
return ($curTimeLocal->isBetween($startTime, $endTime));
}
This example only cares about the hour and minutes and not the seconds but you can easily copy that as well. The key to this is comparing start and end time before comparing them to the current time and add a day to end time if end time is less than start time.
For complete solution which supports all start and end time range you can use bitwise XOR.
/*
* must using hours in 24 hours format e.g. set 0 for 12 pm, 6 for 6 am and 13 for 1 pm
*/
private $startTime = '0';
private $endTime = '6';
$currentHour = \Carbon\Carbon::now()->hour;
$start = $this->startTime > $this->endTime ? !($this->startTime <= $currentHour) : $this->startTime <= $currentHour;
$end = $currentHour < $this->endTime;
if (!($start ^ $end)) {
//Do stuff here if you want exactly between start and end time
}
an updated version of #AliN11's answer taking into account ranges accross two days or in the same day
$now = now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00');
if ($start > $end) {
$end = $end->addDay();
}
if ($now->between($start, $end)||$now->addDay()->between($start, $end)) {
//add statements
}
<?php
$now = date("H");
if ($now < "20") {
echo "Have a good day!";
}
Try this :
$start = 22; //Eg. start hour
$end = 08; //Eg. end hour
$now = Carbon::now('UTC');
if( $start < $now->hour && $now->hour < $end){
// Do something
}
#AliN11's (currently top) answer is good, but doesn't work as one would immediately expect, after midnight it just breaks, as raised in the comments by #Sasha
The solution is to reverse the logic, and check if the time is not between the inverse hours.
Here is an alternative that works as one would expect:
$now = Carbon::now();
$start = Carbon::createFromTimeString('08:00');
$end = Carbon::createFromTimeString('22:00');
if (! $now->between($start, $end)) {
// We're all good
}
Yes, the midnight plays a vital role in time duration. We can find now() being the given time range as follows:
$now = Carbon::now();
$start = Carbon::createFromTime('22', '00');
$end = Carbon::createFromTime('08', '00');
if ($start->gt($end)) {
if ($now->gte($start)) {
$end->addDay();
} elseif ($now->lte($end)) {
$start->subDay();
} else {
return false;
}
}
return $now->between($start, $end);

get the difference in time between two given time

I'm trying to get the difference in time between two given times e.g. first time '17:00:01' and then second time '17:47:25' and here's what I tried so far,
$start_time = "17:00:01";
$end_time = "17:47:25";
echo $start_time->diff($end_time);
But seem's unfortunately not working, any help, ideas please?
My expected output must be like, if no difference in hours but there's difference in minutes and seconds then, "22 mins and 15 secs", If no difference in minutes but have difference in hours then, "2 hrs and 10 secs" but if only seconds in difference then, "22 secs".
Get difference between two times
public function convTimeToMinutes($intime, $outtime)
{
$start = Carbon::parse($intime);
$end = Carbon::parse($outtime);
$minutes = $end->diffInMinutes($start); // 226
return $this->convertMinuteToHours($minutes);
}
public function convertMinuteToHours($minutes)
{
return $minutes / 60;
}
$totalHour = $this->convTimeToMinutes('09:25:35', '13:12:27');
//$totalHour = 3.76
String in php is not object, so can't call diff method on it.
Use diff method, you must change the string to DateTime object.
If you want to compare time difference in same day, you could try:
$start_time = "17:00:01";
$end_time = "17:47:25";
$start_datetime = new DateTime(date('Y-m-d').' '.$start_time);
$end_datetime = new DateTime(date('Y-m-d').' '.$end_time);
var_dump($start_datetime->diff($end_datetime));
Here is it.
PHP
$start_time = "17:00:01";
$end_time = "17:47:25";
$time1 = new DateTime($start_time);
$time2 = new DateTime($end_time);
$interval = $time1->diff($time2);
echo $hour = $interval->format('%h hour');
echo $min = $interval->format('%i min');
echo $sec = $interval->format('%s second');
Output:
0 hour 47 min 24 sec
Now you can add some condition and make the real format.
Just another way of doing it using string functions:
/*
* Get difference in seconds between time formats
*/
function getDiff($start_time, $end_time)
{
$start_time = timeFormatToSeconds($start_time);
$end_time = timeFormatToSeconds($end_time);
if ($end_time > $start_time) {
return $end_time - $start_time;
}
return false;
}
/*
* Convert time format (HH:MM:SS) to seconds
*/
function timeFormatToSeconds($time_format)
{
sscanf($time_format, "%d:%d:%d", $hours, $minutes, $seconds);
return $hours * 3600 + $minutes * 60 + $seconds;
}
$start_time = "17:00:01";
$end_time = "17:47:25";
$diff = getDiff($start_time, $end_time);
if ($diff) {
$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);
$minutes = floor($time / 60);
$time -= $minutes * 60;
$seconds = floor($time);
$time -= $seconds;
var_dump(array($hours, $minutes, $seconds));
}
Convert string time to timestamp and subtract. Convert timestamp to desired time format.
$start_time = strtotime('17:00:01');
$end_time = strtotime('17:47:25');
$diff = $end_time - $start_time;
echo date('H:i:s', $diff);
You can do something like this as a generic function
private function calculateDiffInMinutes($from, $to)
{
$from = Carbon::createFromFormat('Y-m-d H:s:i', $from);
$to = Carbon::createFromFormat('Y-m-d H:s:i', $to);
return $to->diffInMinutes($from);
}
and you can call the function anywhere and pass the parameters you need
here the difference between now and created at time
$this->calculateDiffInMinutes($item->created_at, now())
Hope this helped

PHP calculate between two time with H:i:s format

i'm trying to find and calculate between startime, finish time as: starttime + 1 hour and current time. if current time is between start and finish i must be print message such as please try after 1 hour:
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
echo 'here';
}
this code is not correct and i can not fix that,
You can try this, it shows the difference in minutes:
$current_date_time = new DateTime("now", new DateTimeZone("Asia/Tehran"));
$user_current_time = $current_date_time->format("H:i:s");
$start_limit_time = date("H:i:s",strtotime('2015-09-15 14:57:31'));
$finish_limit_time = date('H:i:s', strtotime($start_limit_time) + (60 * 60 * 1));
$date1 = DateTime::createFromFormat('H:i:s', $user_current_time);
$date2 = DateTime::createFromFormat('H:i:s', $start_limit_time);
$date3 = DateTime::createFromFormat('H:i:s', $finish_limit_time);
if ($date1 > $date2 && $date1 < $date3)
{
$tryAgainIn = $date3->diff( $date1 );
// just minutes
echo "try again in ".$tryAgainIn->format( "%i minutes" );
// or hours and minutes
$hours = $tryAgainIn->format('%h');
$minutes = $tryAgainIn->format('%i');
echo "try again in $hours hours and $minutes minutes";
}
For more information take a look at: DateTime::diff
At first you should avoid operating with strings format, as they should only be used IMHO to printing and retrieving data from outside. Use only timestamp or OOP methods.
I believe, that this is something you are looking for:
$startTime = new DateTime('2015-09-15 14:57:31');
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}
I wonder why you need to use H:i:s format. Can you give some bigger picture?
Edit: Try this, as prior to now I did not fully understand what you want to do ;)
$origin = new DateTime('2015-09-15 14:57:31');
$startTime = new DateTime('today '.$origin->format('H:i:s'));
$endTime = clone $startTime;
$endTime->modify('+1 hour');
if ($startTime->getTimestamp() <= time() && time() < $endTime->getTimestamp()) {
echo 'here';
}

Categories