Convert string "11092018" into date format "11-09-2018"?

-3

How do I transform, for example, a string "11092018" into "11-09-2018" ?

Is there a function I can use?

    
asked by anonymous 11.09.2018 / 13:32

2 answers

3


Using the date_parse_from_format

$data = date_parse_from_format('dmY', '11092018');

$data['month'] = str_pad($data['month'], 2, 0, STR_PAD_LEFT);
$data['day'] = str_pad($data['day'], 2, 0, STR_PAD_LEFT);

$formatada = "{$data['day']}-{$data['month']}-{$data['year']}";

See working at IDEONE .

Manual:

  

link


Using class DateTime::createFromFormat

$data = DateTime::createFromFormat('dmY', '11092018');

$formatada = $data->format('d-m-Y');

See working at IDEONE .

Manual:

  

link


Using the preg_match

if (preg_match('/(\d{2})(\d{2})(\d{4})/', '11092018', $matches)) {
    echo "{$matches[1]}-{$matches[2]}-{$matches[3]}";
}

See working at IDEONE .

Manual:

  

link

    
11.09.2018 / 13:58
4

There are many ways.


Using the substr

$formatada = substr($string,0,2).'-'.substr($string,2,2).'-'.substr($string,4,4);

See working at IDEONE .

Manual:

  

link


Using the substr_replace

$formatada = substr_replace(substr_replace($string,'-',4,0),'-',2,0);

See working at IDEONE .

Manual:

  

link

    
11.09.2018 / 13:43