Showing time only with interval 5 minutes

Discussion in 'PHP' started by basketmen, Oct 17, 2013.

  1. #1
    Hi guys,

    i need showing time only with interval 5 minutes, for example :

    the time now is 00:00, so its showing 00:00
    at 00:01, its should be still showing 00:00
    at 00:02, its should be still showing 00:00

    the time now is 00:05, so its showing 00:05
    at 00:06, its should be still showing 00:05
    at 00:07, its should be still showing 00:05

    and so on

    please help if you can what is the code looks like? gbu for helping
     
    Solved! View solution.
    basketmen, Oct 17, 2013 IP
  2. #2
    [​IMG]

    
    $date = date('H:i', mktime(date('H'), 5 * round(date('i') / 5)));
    
    PHP:
     
    Last edited: Oct 17, 2013
    nico_swd, Oct 17, 2013 IP
    basketmen likes this.
  3. basketmen

    basketmen Well-Known Member

    Messages:
    837
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    130
    #3
    hey many thanks, gbu & liked
     
    basketmen, Oct 17, 2013 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    Uhm... Math.round is going to make 3 show 5... you want Math.floor instead if you want 3 and 4 to be zero.

    Rather than the logic of rounding and two long math operations (mul and div) I'd store date('i') in a var, then subtract modulo 5 from it. It would be a hair faster. In fact if you worked from a second based timestamp and subtracted modulo 300, you'd get the same effect in far less operations.

    // I'm storing time() in $time to be sure there's no rollover errors
    $time5 = date('H:i', ($time = time()) - ($time % 300));
    
    Code (markup):
    It's always easier to subtract the modulo (remainder) than it is to perform div+mul+trunc. Likewise don't waste time converting back and forth between plaintext and an integer. Only use the 'date' function once you have your result!

    Oh, and if you wanted the round off behavior, add 150 to time(). Still cleaner/faster.
     
    Last edited: Oct 17, 2013
    deathshadow, Oct 17, 2013 IP
    PoPSiCLe and nico_swd like this.