Rounding a MYSQL datetime to earliest 15 minute interval in milliseconds (PHP)

后端 未结 4 864
情话喂你
情话喂你 2021-01-15 12:14

I\'m fetching a datetime from MYSQL which looks like:

2010-08-11 11:18:28

I need to convert it into the \"floor\" or the earliest 15 minute interval and outp

相关标签:
4条回答
  • 2021-01-15 12:49

    Would this work? Isn't there some function that would do this better?

    echo floor(strtotime('2010-08-11 11:18:28')/(60*15))*60*15*1000;
    1281505500000
    Wednesday, August 11, 2010 11:15:00 AM
    
    echo floor(strtotime('2010-08-11 11:28:28')/(60*15))*60*15*1000;
    1281505500000
    Wednesday, August 11, 2010 11:15:00 AM
    
    echo floor(strtotime('2010-08-11 00:00:00')/(60*15))*60*15*1000;
    1281465000000
    Wednesday, August 11, 2010 12:00:00 AM
    
    echo floor(strtotime('2010-08-11 23:59:59')/(60*15))*60*15*1000;
    1281550500000
    Wednesday, August 11, 2010 11:45:00 PM
    
    0 讨论(0)
  • 2021-01-15 12:49

    The following will give you the earliest 15 minute interval :

    select UNIX_TIMESTAMP(YOURDATETIME)-MOD(UNIX_TIMESTAMP(YOURDATETIME), 900) 
    from YOURTABLE
    

    The result is in epoch seconds (seconds since '1970-01-01 00:00:00' UTC), if you want that value in milliseconds you should multiply by 1000 (either in the query or in PHP, as you see fit).

    EDIT

    In PHP for your set of values that would be :

    $values = array('2010-08-11 11:18:28', '2010-08-11 11:28:28', '2010-08-11 00:00:00', '2010-08-11 23:59:59');
    foreach($values as $value) {
        $result = (strtotime($value)-(strtotime($value) % 900));
        echo "$value -> $result\n";
    }
    

    When you multiply $result by 1000 (to get the value in ms) you will probably get an overflow and the result will be converted to a float. This is probably not what you want, so you might be better of using bcmul :

    $result = bcmul((strtotime($value)-(strtotime($value) % 900)), 1000);
    
    0 讨论(0)
  • 2021-01-15 12:50

    Give this a try and see what happens:

    select DATE(myColumn) 
           + CONVERT(HOUR(myColumn),CHAR(2)) + ':'
           + CASE 
             WHEN MINUTE(myColumn) < 15 THEN '00'
             WHEN MINUTE(myColumn) < 30 THEN '15'
             WHEN MINUTE(myColumn) < 45 THEN '30'
             ELSE '45'
           END 
           + ':00' as myDate
    
    0 讨论(0)
  • 2021-01-15 12:57

    Ok, let's see the worst solution:

    <?php
    
    $ts    = explode(' ', '2010-08-11 11:18:28');
    $date  = explode('-', $ts[0]);
    $time  = explode(':', $ts[1]);
    $ts    = mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
    $floor = mktime($time[0], round($time[1]/15)*15, 0, $date[1], $date[2], $date[0]);
    
    0 讨论(0)
提交回复
热议问题