time difference calculating using php? - php

I find it difficult to calculate time difference using PHP. How to calculate time difference in HH:MM:SS format (hours:minutes:seconds) between two different dates?
For example, the input is:
$start_time : 19:30
$end_time : 7:30,
$currenttime = 21:30
I have to find out current time has match with given start time and end time.

Convert the times to a timestamp value, which is an integer value in seconds. Then, you can subtract them easily to get the difference in seconds. After that, it's pretty straightforward to convert that back to hours and minutes.

$iStart = strtotime( '00:00:00' );
$iEnd = strtotime( '12:00:00' );
$iCurrent = strtotime( date('H:i:s') );
if( $iCurrent > $iStart && $iCurrent < $iEnd ) {
echo "active!";
} else {
echo "not active";
}
This will only respect the time (it will be active once a day).
If you need specific dates you can use:
$iStart = strtotime( '2012-12-01 00:00:00' );
$iEnd = strtotime( '2012-12-31 12:00:00' );
$iCurrent = time();
if( $iCurrent > $iStart && $iCurrent < $iEnd ) {
echo "active!";
} else {
echo "not active";
}

Related

calculate night hours between two date

I want to calculate night hours (21PM to 6AM) between two given dates.
I don't have any ideas
public function biss_hours($start, $end){
$startDate = new \DateTime($start);
$endDate = new \DateTime($end);
$periodInterval = new \DateInterval( "PT1H" );
$period = new \DatePeriod( $startDate, $periodInterval, $endDate );
$count = 0;
foreach($period as $date){
$startofday = clone $date;
$startofday->setTime(5,59);
$endofday = clone $date;
$endofday->setTime(20,59);
if($date > $startofday && $date < $endofday){
$count++;
}
}
return $count;
}
I have this fonction but it's don't work :)
Thx any help
There is no need to loop over a period. As already suggested in the comments, start by calculating the hours of the start and end date since these are the ones that can actually contain less than a full nights hours. Once those are calculated, you can simply get the number of days remaining and multiply them by the amount of hours a night has.
Please note that I only consider hours in my example below, so 22:55 to 24:00 would result in 2 full hours of night time counted. Also it does not check cases where the end date is before the start date or whether inputs are valid. It should get the idea across though:
function getHoursForSingleDay ( $startTime, $endTime, $nightStart, $nightEnd ) {
$numHours = 0;
// if the day starts before night ends
if( $startTime < $nightEnd ) {
// e.g. Night ends at 6a.m. - day starts at 5 a.m. = 1 hour
$numHours += $nightEnd - $startTime;
}
// if the day ends after night starts
if( $endTime > $nightStart ) {
// e.g. day ends at 23 - night starts at 21 = 2 hours
$numHours += $endTime - $nightStart;
}
return $numHours;
}
function biss_hours ( $start, $end, $nightStart = 21, $nightEnd = 6 ) {
$startDate = new \DateTime( $start );
$endDate = new \DateTime( $end );
$startTime = intval( $startDate->format( 'H' ) );
$endTime = intval( $endDate->format( 'H' ) );
// Both dates being the same day is an edge case
if( $startDate->format( 'Y-m-d' ) === $endDate->format( 'Y-m-d' ) ) {
return getHoursForSingleDay( $startTime, $endTime, $nightStart, $nightEnd );
}
// get the hours for bot the start and end date, since they can be less than a full night
$numHours = getHoursForSingleDay( $startTime, 24, $nightStart, $nightEnd );
$numHours += getHoursForSingleDay( 0, $endTime, $nightStart, $nightEnd );
// all remaining days in between can be calculated in a rather simple way
$nightHoursPerDay = $nightEnd + ( 24 - $nightStart );
// -1 because diff returns 1 for two adjacent days, but we treat the first and last day specially
$numDaysBetween = intval( $endDate->diff( $startDate )->format( "%a" ) ) - 1;
$numHours += $numDaysBetween * $nightHoursPerDay;
return $numHours;
}

Run functions when current time is outside user metadata database times

I have a somewhat complicated time equation that had been driving me mental!
What I have so far is:
$current = time(); // UTC time
$user_in = '8:00 am'; // local time
$user_out = '4:00 pm'; // local time
$gmt_off = '11'; // Australia EST (+1 at the moment)
I then have the function that will convert the local time to UTC by subtracting the GMT offset, and output it as g:i a
function utc( $time ) {
$time = ( empty($time) ? null : strtotime($time) );
$gmt = '60 * 60 * 11'; // there is an actual check for it to be 10 or 11 - and in seconds
$out = ( $time - $gmt );
$out = date( 'Y-m-d g:i a', $out );
return $out;
}
What I cannot figure out is how to properly configure the conditions to check if the current time is outside the $user times
$user_in_utc = utc( $user_in );
$user_out_utc = utc( $user_out );
if( $current < $user_in_utc && $current > $user_out_utc ) {
// do something
}
However, the problem I'm running into is that say current time is 6:00pm local time.
How do I check it is now currently less than $user_out when it keeps saying the date is today and not tomorrow?
I intend for these functions to run if the statement being true as a cron task
Just use date_default_timezone_set and strtotime to get your timestamp values, and they will all be in the same timezone and hence directly comparable. Note that your condition should use || (or) rather than && (and) to check if the time is outside user hours.
date_default_timezone_set('Australia/Sydney');
$current = strtotime('now');
$user_in = strtotime('8:00 am');
$user_out = strtotime('4:00 pm');
if( $current < $user_in || $current > $user_out ) {
// do something
}

How to check the time range in array are exist in between two time variable in PHP

I have this time range in array example:
$timerange = array('01:30:00','01:31:00',...........,'02:30:00');
and 2 variable:
$start_time = '01:15:00';
$end_time = '03:29:00';
if($timerange is between $start_time && $end_time)
{
//do it something if yes.....
}
Please help me, its have any ready function to use in PHP? to check on this.
You need not bother with conversions of your time strings to a time type - you can compare the strings as they are:
<?php
$timerange = array('01:30:00', '01:31:00', '01:32:00', '02:30:00');
$start_time = '01:15:00';
$end_time = '03:29:00';
$between = array();
foreach ($timerange as $time)
if ($start_time <= $time && $time <= $end_time) $between[] = $time;
if ($between)
{
echo "These are the times between $start_time and $end_time:\n";
print_r($between);
}
If you like it better, you can replace the foreach loop with array_filter():
$between = array_filter($timerange,
function($time) use ($start_time, $end_time)
{ return $start_time <= $time && $time <= $end_time; }
);
<?php
$timerange = array(strtotime('01:30:00'), strtotime('01:31:00'), strtotime('03:30:00'));
$start_time = strtotime('01:15:00');
$end_time = strtotime('03:29:00');
foreach($timerange as $key => $text_field){
if($timerange[$key] > $start_time && $timerange[$key] < $end_time){
echo "Existing";
}else{
echo "Not Existing";
}
}
?>
See How to check if a date is in a given range?
Edit: As you are looking in a 24 hour range you can pick and random date when constructing your timestamps and your calculations should hold true as all of them are the same date.
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
Where all of those are timestamps.
Also look at this PHP check if time falls within range, questioning common solution if you don't want this to depend on the date but just the time.

How can I use a variable in a date diff function?

I am using an ACF Field to allow a client to content manage a countdown to their next event I am using JS flip clock on the desktop version but as it isn't responsive, I decided to use date diff to echo out just the number of days for mobile.
The site is currently live at theindustrialproject.co.uk
The code I currently have is this:
<?php
$date1 = date_create(date());
$date2 = date_create(the_field('mobile_date'));
$diff = date_diff($date1,$date2);
$difference = $diff;
if ($difference < 0) { $difference = 0; }
echo '<span class="countdown-mobile">'. floor($difference/60/60/24)."</span><br />";
if ($difference == 1) { echo "<p>Day</p>"; }
else { echo "<p>Days</p>"; }
?>
but it always returns 0. For reference, I pulled the code from here
Without knowing what the function the_field('mobile_date') will return ( either a date or timestamp? ) you might need to alter that particular line below but you should be able to use the DateTime object and format the difference like this
$format='Y-m-d';
$timezone=new DateTimeZone('Europe/London');
/* We need 2 datetime objects - one for now the other for the future date */
$now=new DateTime( date( $format, strtotime('now') ), $timezone );
$target=new DateTime( the_field('mobile_date'), $timezone );
/* Format the difference in days */
$days = $now->diff( $target )->days;
echo "<span class='countdown-mobile'>{$days}</span><br />" . ( $days == 1 ? '<p>Day</p>' : '<p>Days</p>' );

Display times in 24hr... can I just show the hour if it's not 30 minutes past?

Is there a way to only show the hours of a time if it's not 30 minutes past, but show :30 for when the time is 30 minutes past?
http://new.clairvoyant.co/details/?Pin=4378 This is my page. In the schedule you can see when the blocks are really short, it's a real struggle to display the time period within them.
What'd I'd like to do is to show a format like 12pm - 4pm if the start and end time are just hours. And show 12pm - 4:30pm if one of them is 30 minutes.
Is this able to done just by formatting strttotime? The input variable is in 24hour (24:00:00). The ending output is formatting into 12 hour.
$Start12 = strtotime($Shift['Start']);
$Stop12 = strtotime($Shift['Stop']);
And is outputted like:
<span class='c'>".date('g:ia',$Start12)." to ".date('g:ia',$Stop12)."</span>
Assuming that the only number of minutes will be 30:
function printDate30($date){
if(date('i',$date) == 30){
return date('g:ia',$date);
}else{
return date('ga',$date);
}
}
and use
echo "<span class='c'>".printDate30($Start12)." to ".printDate30($Stop12)."</span>";
Demo: http://codepad.org/c2AhcELC
Here's a good example mate, I've not syntax checked this though:
// Create a new object from your start time
$firstDateTime = new DateTime( strtotime( $Shift['Start'] ) );
$firstDateTimeFormatter = 'H'; // Set the object to be default formatted for the hour only
// Repeat, blah...
$secondDateTime = new DateTime( strtotime( $Shift['Stop'] ) );
$secondDateTimeFormatter = 'H';
// If the minutes for this object are not 00 then we want to format the time
// differently, these two checks do that
if( $firstDateTime->format('i') != '00' )
$firstDateTimeFormatter = 'H:m';
if( $secondDateTime->format('i') != '00' )
$secondDateTimeFormatter = 'H:m';
// See the results
echo $firstDateTime->format( $firstDateTimeFormatter );
echo $secondDateTime->format( $secondDateTimeFormatter );
// Put this into a convenient function to use
function formatTime( $time )
{
$dt = new DateTime( strtotime( $time ) );
return ( $dt->format('i') != '00' ? $dt->format('H:i') : $dt->format('H') );
}

Categories