php function to invert data [duplicate]

2

I've put together a very simple function to invert the date, see:

function inverteData($data) {
   if(count(explode("/",$data)) > 1){
      return implode("-",array_reverse(explode("/",$data)));
   }
   else if(count(explode("-",$data)) > 1) {
      return implode("/",array_reverse(explode("-",$data)));
   }
}

Example 1 of how it works:

inverteData("10/02/2006"); 

It returns me 2006-02-10

Example 2 of how it works:

inverteData("2006-02-10"); 

It returns me 10/02/2006

Well I need to make it convert the following date as well: (200206) to (2006-02-20).

Can anyone help me?

    
asked by anonymous 15.09.2016 / 15:41

3 answers

4

One way would be to use substr :

function inverteData($data) {
    if (count(explode("/", $data)) > 1) {
        return implode("-", array_reverse(explode("/", $data)));
    } elseif (count(explode("-", $data)) > 1) {
        return implode("/", array_reverse(explode("-", $data)));
    }else{
        return '20' . substr($data,4,2) . '-' . substr($data,2,2) . '-' . substr($data,0,2);
    }
}


echo inverteData('200206'); // retorna: 2006-02-20
    
15.09.2016 / 15:55
2

I would do with date operation , it does not have if within the method and would be free depending on settings :

function data_format($format_ini, $value, $format_end)
{
    $d = \DateTime::createFromFormat($format_ini, $value);
    if ($d)
    {
        return $d->format($format_end);
    }
    return null;
}


echo data_format("d/m/Y", "10/02/2006", "Y-m-d");
echo '<br>';
echo data_format("Y-m-d", "2006-02-10", "d/m/Y");
echo '<br>';
echo data_format("dmy", "200206", "Y-m-d");

Example

    
15.09.2016 / 16:15
1

Using REGEX, I think it's all simpler.

function reverseDate($date, $hours = true){

    $patternBR  = '~(\d{2})/(\d{2})/(\d{2,4})( (\d{2}):(\d{2}):(\d{2}))?~';
    $patternEUA = '~(\d{2,4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?~';

    preg_match($patternBR, $date, $match);
    $isDateBR = !empty($match);

    if(!$isDateBR){
        preg_match($patternEUA, $date, $match);
    }

    if(empty($match)){
        throw new Exception("Error Processing Request", 1);
    }

    $formatBR = '%s/%s/%s';
    $formatEUA = '%s-%s-%s';
    $format = $isDateBR?$formatEUA:$formatBR;

    $date = sprintf($format, $match[3], $match[2], $match[1]);
    if($hours){
        if(isset($match[5])){
            $date .= sprintf(' %s:%s:%s', $match[5], $match[6], $match[7]);
        }else{
            $date .= (' '.date('h:i:s'));
        }
    }
    return $date;
}

echo reverseDate(date('Y-m-d'));    # 15/09/2016 11:20:45
echo reverseDate(date('d/m/Y'));    # 2016-09-15 11:20:45
echo reverseDate(date('y-m-d'));    # 15/09/16 11:20:45
echo reverseDate(date('d/m/y'));    # 16-09-15 11:20:45
    
15.09.2016 / 16:22