Date - date_trunc for PHP

1

PostgreSQL has a date function called date_trunc

How can I play it in PHP?

I only need the options:

  • second
  • minute
  • hour
  • day
  • week
  • month
  • quarter
  • year
asked by anonymous 30.10.2015 / 18:03

1 answer

1

Resolution

Auxiliary Functions

// REMOVE TUDO QUE NAO SEJA NUMERO, DA STRING
function onlyNumber($var){
    return preg_replace('/\D/', '', $var);
}

// AJUSTA OS NUMEROS A MASK PASSADA
function maskNumber($mask, $str){
    $str = onlyNumber($str);
    $return = '';

    for($i = 0, $j = 0; $i < strlen($mask); $i++){
        if($mask[$i] == '#' && isset($str[$j])){
            $return .= $str[$j++];
        }else{
            $return .= $mask[$i];
        }
    }

    return $return;
}

date_trunc function

function date_trunc($field, $source){

    $source = maskNumber('####-##-## ##:##:##', $source);
    $source = str_replace('#', '0', $source);

    $date['year']   = 'Y-01-01 00:00:00';
    $date['mount']  = 'Y-m-01 00:00:00';
    $date['day']    = 'Y-m-d 00:00:00';

    $date['hour']   = 'Y-m-d H:00:00';
    $date['minute'] = 'Y-m-d H:i:00';
    $date['second'] = 'Y-m-d H:i:s';

    if(in_array($field, array_keys($date))){
        return date($date[$field], strtotime($source));
    }else{
        if($field == 'week'){
            return date($date['day'], strtotime("last Monday", strtotime($source)));
        }
        if($field == 'quarter'){
            $mount = explode('-', $source);
            $mount = $mount[1];
            $quarter = array(1=>'01',2=>'04',3=>'07',4=>'10');
            return date(sprintf('Y-%s-01 00:00:00', $quarter[ceil($mount/3)]), strtotime($source));
        }
        return date($date['day'], strtotime($source));
    }
}

Tests

date_trunc('day', '2015-10-30 14:48:15');       // 2015-10-30 00:00:00
date_trunc('week', '2015-10-30 14:48:15');      // 2015-10-26 00:00:00
date_trunc('mount', '2015-10-30 14:48:15');     // 2015-10-01 00:00:00
date_trunc('quarter', '2015-11-25 14:48:15');   // 2015-10-01 00:00:00
date_trunc('year', '2015-10-30 14:48:15');      // 2015-01-01 00:00:00
    
30.10.2015 / 18:04