How to round unix timestamp up and down to nearest half hour?

后端 未结 10 2056
名媛妹妹
名媛妹妹 2020-12-14 17:16

Ok so I am working on a calendar application within my CRM system and I need to find the upper and lower bounds of the half an hour surrorunding the timestamp at which someb

10条回答
  •  粉色の甜心
    2020-12-14 17:43

    PHP does have a DateTime class and a whole slough of methods that it provides. You could use these if you like, but I find it easier to use the built-in date() and strtotime() functions.

    Here's my solution:

    // Assume $timestamp has the original timestamp, i.e. 2012-03-09 16:23:41
    
    $day = date( 'Y-m-d', $timestamp ); // $day is now "2012-03-09"
    $hour = (int)date( 'H', $timestamp ); // $hour is now (int)16
    $minute = (int)date( 'i', $timestamp ); // $minute is now (int)23
    
    if( $minute < 30 ){
      $windowStart = strtotime( "$day $hour:00:00" );
      $windowEnd   = strtotime( "$day $hour:30:00" );
    } else {
      $windowStart = strtotime( "$day $hour:30:00" );
      if( ++$hour > 23 ){
        // if we crossed midnight, fix the date and set the hour to 00
        $day = date( 'Y-m-d', $timestamp + (24*60*60) );
        $hour = '00';
      }
      $windowEnd   = strtotime( "$day $hour:00:00" );
    }
    
    // Now $windowStart and $windowEnd are the unix timestamps of your endpoints
    

    There are a few improvements that can be made on this, but that's the basic core.

    [Edit: corrected my variable names!]

    [Edit: I've revisited this answer because, to my embarrassment, I realized that it didn't handle the last half-hour of a day correctly. I've fixed that issue. Note that $day is fixed by adding a day's worth of seconds to the timestamp -- doing it this way means we don't have to worry about crossing month boundaries, leap days, etc. because PHP will format it correctly for us regardless.]

提交回复
热议问题