DCJones
DCJones

Reputation: 3471

Calculating minutes left in the day

I am trying to calculate how many minutes are left on any given day. I thought I had the soluion but the numbers look a little odd.

My code:

date_default_timezone_set('Europe/London');
$sTime = date("d-m-Y H:i:s");  
echo 'The time is: ' . $sTime."<br>";


$NowTime = date("H:i");

echo $NowTime."<br>";

$start = strtotime($NowTime);
$stop = strtotime("23:59");

$diff = ($stop - $start); //Diff in seconds

echo "start ". $start."<br>";
echo "stop " .$stop."<br>";
echo "diff " .$diff."<br>";

$minutes = $diff / 60;

echo "minutes ". $minutes."<br>";

$hours = $minutes / 60;

echo "hours " .$hours."<br>";

The ouput:

15:24

start 1446909840

stop 1446940740

diff 30900

H : M 08:35:00

minutes 515

hours 8.58333333333

Question: How do I convert the hours "8.58333333333" to 8.xx minutes.

Many thanks for your time.

Upvotes: 2

Views: 2117

Answers (2)

Wynn
Wynn

Reputation: 207

I have a fx that calculate time-diff by days, hours, min, or seconds. Feed in the dates and get the results back. Pos or negative results depending on how you feed it in.

$ApptHourTillMidnight=  (GetTimeDiff( date('Y-m-d 23:59:59'),date('Y-m-d H:i:s'),'m') ); //get minutes until midnight

function GetSeconds($time){
$seconds = strtotime($time); return $seconds;

}

function GetTimeDiff($time1,$time2,$type){
$s= GetSeconds($time1);
$e= GetSeconds($time2);
switch (strtolower($type)) {
    case "s";
        return ($s - $e);
    case "m";
        return (($s - $e) / 60);
    case "h";
        return ((($s - $e) / 60)/60);
    case "d";
        return (((($s - $e) / 60)/60)/24);
    return FALSE;  //wrong type
}

}

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33823

If you have access to the DateTime class you can do this quite easily.

        $timezone=new DateTimeZone( 'Europe/London' );
        $now=new DateTime( 'now', $timezone );
        $midnight=new DateTime( date('Y-m-d H:i:s', strtotime('11.59pm') ), $timezone );
        $diff = $now->diff( $midnight );
        $mins=( intval( $diff->format('%h') ) * 60 ) + intval( $diff->format('%i') );

        echo $diff->format('%h hours %i minutes %s seconds').'<br />Minutes left until midnight: '.$mins;

Upvotes: 2

Related Questions