Question

How can I get the last/previous half hour mark using PHP date/time.

So the time 15:31 all the way through to 16:29 should give 15:30 since that's the last half hour mark.

And I want to be able to dynamically change the minutes. So if I set the minutes to 15, it'll get the last/previous :15 minute mark So 15:16 through to 16:14 will return 15:15

This is what I have but I just can't get it to work...

function newtime($time, $offset) {
                                $prev = $time - $offset;
                                $newtime = ($offset > 900) ? ($prev - 1800) : ($prev);
                                return $newtime;
                            }

                            $hours = date("H", time());
                            $minutes = date("m", time());               
                            echo 'Current date: ' . date("Y-m-d H:i:s", time()) . '<br/>';
                            $time = strtotime("2013-01-23 15:35:00");
                            echo 'time: ' . date("Y-m-d H:i:s", $time) . '<br/>';
                            $offset = ($time % 1800);
                            echo 'prev: ' . $offset . '<br/>';
                            $newtime = newtime($time, $offset);
                            echo date("Y-m-d H:i:s", $newtime) . '<br/><br/>';

It's really tough, I just can't wrap my head around it.

Any help is greatly appreciated!

Was it helpful?

Solution

Try something like this:

<?
function newtime($time,$minute=30){
    $time=strtotime($time);
    $m=date("i",$time)*1;
    $h=date("H",$time)*1;
    if($m<$minute){
        $h=$h-1;
    }
    return date("H:i",strtotime($h.":".$minute));
}

print newtime("15:31");
//OUTPUT: 15:30
print newtime("16:29");
//OUTPUT: 15:30

print newtime("15:16",15);
//OUTPUT: 15:15
print newtime("16:14",15);
//OUTPUT: 15:15
?>

OTHER TIPS

function newtime ($time, $offset)
{
    // First, calculate the offset in seconds:
    $offset_sec = $offset * 60;

    // Next, fetch unix timestamp from $time
    $unix_time = strtotime($time);

    // Then calculate the modulo
    $modulo = $unix_time % $offset_sec;

    // Calculate latest timestamp
    $last_time = $unix_time - $modulo;

    // Display latest timestamp
    return date('H:i',$last_time);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top