Format value for date [closed]

-2

I need to format a value for date ... I search for the following value link:

  

20181107

In case it would be 07/11/2018, today. I need to get this value and format it in 2018-11-07 format, I tried it as follows:

date('Y-m-d', strtotime('20181107'));

But in some cases it puts the day in the place of the month, then I wanted a solution for that or just a code that inserted a hyphen after 4 digits and after 6 digits, it would be simpler too.

    
asked by anonymous 07.11.2018 / 14:48

4 answers

7

You can use the createFromFormat function of the DateTime object:

<?php
    echo DateTime::createFromFormat('Ymd', '20181107')->format('Y-m-d');
?>

In this way you can define the input format, and in the format function, you define the output format.

See working at Ideone .

You can also see more about createFromFormat here .

    
07.11.2018 / 15:00
2

Nicholas,

You can use a common substring to do this, if your case is just string formatting, follow below:

substr("20181107",0,4)."-".substr("20181107",4,2)."-".substr("20181107",6,2)
    
07.11.2018 / 14:55
1

It has already been replied, but if you prefer the procedural way, you can do this:

$date = date_create_from_format('Ymd', '20180120');
echo date_format($date, 'Y-m-d');

The functions date_create_from_format and date_format correspond to DateTime::createFromFormat and DateTime::format , respectively.

    
07.11.2018 / 15:12
0

To turn this 20181107 into this 2018-11-07

 $str="20181107";

 $data = date("Y-m-d", strtotime($str));

ideone

strtotime - Interprets any date / time description in English text in Unix timestamp

Date format that the strtotime () interpreter understands: ISO8601% 20181107

See more formats in Date Formats that the strtotime (), DateTime, and date_create () understand

    
07.11.2018 / 19:48