I've read that this function should work in 5.3 but not 5.2 so I am unsure why I am getting fatal errors from PHP. Sadly I am not a coder by any means, was hoping I could get some guidance. Thanks!
function date_diff($start, $end="NOW")
{
$sdate = strtotime($start);
$edate = strtotime($end);
$time = $edate - $sdate;
if($time>=86400) {
// Days + Hours + Minutes
$pday = ($edate - $sdate) / 86400;
$preday = explode('.',$pday);
$phour = $pday-$preday[0];
$prehour = explode('.',$phour*24);
$premin = ($phour*24)-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $preday[0];
}else{
$timeshift = 0;
}
return $timeshift;
}
Cannot redeclare XXXX() simply means that you are trying to declare somethign that already exists.
The date_diff function has already been defined so check if it is already defined before defining it again. You can do this using function_exists()
if (!function_exists("date_diff"))
{
function date_diff($start, $end="NOW")
{
$sdate = strtotime($start);
$edate = strtotime($end);
$time = $edate - $sdate;
if($time>=86400) {
// Days + Hours + Minutes
$pday = ($edate - $sdate) / 86400;
$preday = explode('.',$pday);
$phour = $pday-$preday[0];
$prehour = explode('.',$phour*24);
$premin = ($phour*24)-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $preday[0];
}else{
$timeshift = 0;
}
return $timeshift;
}
}
Just to clarify, you only need to define the function like this is you want your code to work on versions of php newer AND older than 5.3 If you are only using 5.3+ then you do not need to declare this function at all as it already exists, you can just use date_diff() without defining it
Related
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;
*/
}
}
$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);
So I have a piece of code on a certain page of my site that does things with timestamps. Pretty much what it does is there is a UNIX timestamp that is placed in the database from each individual Purchase Order. Once a certain amount of time has passed and nothing has been done to that Purchase Order then an indication will begin flashing on the page with the amount of hours that is past due. Once someone takes action then the flashing indication goes away.
Now, everything is working perfectly fine. The issue I am having is that the indicator should only take Monday thru Friday into account. Not the weekends. Also, I've set the hours from 9am to 5pm est but the code seems to 100% skip all these restrictions and just takes all days and times into consideration.
I've placed the code below and as you can see I've set the restrictions of days and time but it seems to be voided somehow. Any help would be much appreciated with this issue.
$current_stardate = time();
$past_stardate = $stardate['time_stamp'];
$placer = ($current_stardate - $past_stardate) / 3600;
$from = date("Y-m-d H:i:s", $current_stardate);
$to = date("Y-m-d H:i:s", $past_stardate);
define('DAY_WORK', 28800); // 9 * 60 * 60
define('HOUR_START_DAY', '09:00:00');
define('HOUR_END_DAY', '17:00:00');
$date_begin = $to;
$date_end = $from;
$d1 = new DateTime($date_begin);
$d2 = new DateTime($date_end);
$period_start = new DateTime($d1->format('Y-m-d 00:00:00'));
$period_end = new DateTime($d2->format('Y-m-d 23:59:59'));
$interval = new DateInterval('P1D');
$period = new DatePeriod($period_start, $interval, $period_end);
$worked_time = 0;
$nb = 0;
foreach($period as $date){
$week_day = $date->format('w'); // 0 (for Sunday) through 6 (for Saturday)
if (!in_array($week_day,array(1, 5)))
{
if ($date->format('Y-m-d') == $d1->format('Y-m-d'))
{
$end_of_day_format = $date->format('Y-m-d '.HOUR_END_DAY);
$d1_format = $d1->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $end_of_day->diff($d1)->format("%H:%I:%S");
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else if ($date->format('Y-m-d') == $d2->format('Y-m-d'))
{
$start_of_day = new DateTime($date->format('Y-m-d '.HOUR_START_DAY));
$d2_format = $d2->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $start_of_day->diff($d2)->format('%H:%I:%S');
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else
{
$worked_time += DAY_WORK;
}
}
if ($nb> 10)
die("die ".$nb);
}
$the_work = $worked_time/60/60;
$genesis_stardate = strtotime($stardate['date_purchased']);
if($past_stardate == NULL)
{
$the_work = NULL;
$future_days = NULL;
}
else
{
$future_days = ($current_stardate - $past_stardate) / 3600;
}
$date is not defined. Try to define it, and the problem should be solved.
I want the diff between two date-time in php. I want diff in H:i:s format. Here is my code.
$start_date = 2013-08-13;
$end_date = 2013-08-23;
$start_time = 12:28:58;
$end_time = 13:16:45;
$h1 = substr("$start_time",0,-6);
$i1 = substr("$start_time",3,-3);
$s1 = substr("$start_time",6);
$h2 = substr("$end_time",0,-6);
$i2 = substr("$end_time",3,-3);
$s2 = substr("$end_time",6);
$m1 = substr("$start_date",5,-3);
$d1 = substr("$start_date",8);
$y1 = substr("$start_date",0,-6);
$m2 = substr("$end_date",5,-3);
$d2 = substr("$end_date",8);
$y2 = substr("$end_date",0,-6);
$r1=date("Y-m-d H:i:s",mktime($h1,$i1,$s1,$m1,$d1,$y1));
$r2=date("Y-m-d H:i:s",mktime($h2,$i2,$s2,$m2,$d2,$y2));
Why are you performing all those operations when you can use strtotime() ?
It is simpler: if you join dates with times with a space then you can use the aforementioned function to generate a timestamp.
Then, you obtain the difference between the two just with a simple calculation.
Finally, you will format the resulting timestamp with date("H:i:s") (in your case).
Here's the code.
$start_date = "2013-08-13";
$end_date = "2013-08-23";
$start_time = "12:28:58";
$end_time = "13:16:45";
$start_date = $start_date." ".$start_time;
$end_date = $end_date." ".$end_time;
$start_date = strtotime($start_date);
$end_date = strtotime($end_date);
$difference = $end_date - $start_date;
echo date("H:i:s", $difference);
DateTime is the right tool for this job:-
$start_date = '2013-08-13';
$end_date = '2013-08-23';
$start_time = '12:28:58';
$end_time = '13:16:45';
$start = new \DateTime($start_date . ' ' . $start_time);
$end = new \DateTime($end_date . ' ' . $end_time);
$diff = $start->diff($end, true);
$diff is an instance of DateInterval, so you can use DateInterval::format() to echo out the time:-
echo $diff->format("%H:%I:%S");
This is what i used. And its working. If any suggestion please tell. Thanks To all for your reply.
function ensure2Digit($number) {
if($number < 10)
{
$number = '0'.$number;
}
return $number;
}
$start_date = "2013-08-13";
$end_date = "2013-08-23";
$start_time = "12:28:58";
$end_time = "13:16:45";
$start_date = $start_date." ".$start_time;
$end_date = $end_date." ".$end_time;
$start_date = strtotime($start_date);
$end_date = strtotime($end_date);
$difference = $end_date - $start_date;
$h = ensure2Digit(floor($difference / 3600));
$m = ensure2Digit(floor(($difference / 60) % 60));
$s = ensure2Digit($difference % 60);
$time_taken = $h.":".$m.":".$s;
Just whipped up this:
function sec_diff($date_ini, $date_end, $time_ini='00:00:00', $time_end='00:00:00')
{
$d_ini=explode('-', $date_ini);
$h_ini=explode(':', $time_ini);
$d_end=explode('-', $date_end);
$h_end=explode(':', $time_end);
$t_ini=mktime($h_ini[0], $h_ini[1], $h_ini[2], $d_ini[1], $d_ini[2], $d_ini[0]);
$t_end=mktime($h_end[0], $h_end[1], $h_end[2], $d_end[1], $d_end[2], $d_end[0]);
return $t_end-$t_ini;
}
It will get you the difference in seconds. You can easily operate on the result to get the desired format: result / 3600 will give you hours. The rest of that operation will give you spare seconds, that you can / 60 to get minutes. Any rest are seconds.
//Difference between 2 dates
This function works well but display wrong time format. Pls how can I change the time of this function from GMT to GMT+1? Displays 15hrs 22mins instead of 16hrs 22mins.
Thanks
function get_date_diff($start, $end="NOW")
{
$sdate = strtotime($start);
$edate = strtotime($end);
$timeshift = "";
$time = $edate - $sdate;
if($time>=0 && $time<=59) {
// Seconds
$timeshift = $time.' seconds ';
} elseif($time>=60 && $time<=3599) {
// Minutes + Seconds
$pmin = ($edate - $sdate) / 60;
$premin = explode('.', $pmin);
$presec = $pmin-$premin[0];
$sec = $presec*60;
$timeshift = $premin[0].' min '.round($sec,0).' sec '."<b>ago</b>";
} elseif($time>=3600 && $time<=86399) {
// Hours + Minutes
$phour = ($edate - $sdate) / 3600;
$prehour = explode('.',$phour);
$premin = $phour-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec '."<b>ago</b>";
} elseif($time>=86400) {
// Days + Hours + Minutes
$pday = ($edate - $sdate) / 86400;
$preday = explode('.',$pday);
$phour = $pday-$preday[0];
$prehour = explode('.',$phour*24);
$premin = ($phour*24)-$prehour[0];
$min = explode('.',$premin*60);
$presec = '0.'.$min[1];
$sec = $presec*60;
$timeshift = $preday[0].' days '.$prehour[0].' hrs '.$min[0].' min '.round($sec,0).' sec '."<b>ago</b>";
}
return $timeshift;
}
Set the timezone using the date_default_timezone_set() function. If that doesn't work, you have PHP <5.1.0 and should set the TZ environment variable. Check here for the detailed order of preference used to determine the timezone.
You could also skip all that code you wrote and use the date() function to get the resulting datetime string in pretty much any format you desire.