Format value for date

Asked

Viewed 123 times

-2

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

20181107

No case would be 07/11/2018, today. I need to take this value and format in format 2018-11-07, I tried it this way:

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

However, in some cases he puts the day in the place of the month, there wanted a solution to this or just a code that inserted a hyphen after 4 digits and after 6 digits, it would be simpler too.

  • 2

    Can you tell in which cases you happen to put the day in the place of the month? I could not reproduce.

  • It may not apply to you (you don’t want to use it for many reasons), but if you have to deal with dates often, it might be worth a look at the library Carbon. Even she is the standard lib adopted by Laravel.

  • 1

    "Put the day in place of the month"... Who does it? PHP or url return?

3 answers

7


You can use the function createFromFormat of the object DateTime:

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

This way you can define the input format, and in the function format, you set the output format.

See working on Ideone.

You can also see more about the createFromFormat here.

1

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)
  • You even tested what you sent me?

  • @Nicholasruschelkrüger You tested and it didn’t work?

  • 2

    @Nicholasruschelkrüger put the code in javascript, sorry! kkkk ajustei for php, abs!

1

It has already been answered, but if you prefer the procedural way, you can do so:

$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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.