Format date written "ex. January 12, 2017" to default (Y-m-d)

Asked

Viewed 131 times

0

It is possible to pass a date in this standard "January 12, 2017" to the American standard (Y-m-d) ?

Some example?

Thank you.

  • You want to turn a string into date, or you want to format the output of a truth date?

  • Thanks for the help, I want the output to be a valid date in American format to add in the database.

  • 5

    But is the input a date or a string? If it’s date, a simple date('Y-m-d') is enough. And that’s NOT American standard. Incidentally, it is important [Dit] the question and explain better what he wants, not everyone reads comments. (actually not everyone reads the right question).

  • Note, this is not American standard. It is the ISO 8601 https://en.wikipedia.org/w/index.php?title=ISO_8601&mobileaction=toggle_view_desktopstandard

2 answers

3


Using the function date_create_from_format you can format the date as you want but first you should make some changes:

$string = "12 de Dezembro de 2017";

$string = preg_replace('/( de ){1,2}/', ' ', $string);

$month = [
        'Janeiro' => 'January',
        'Fevereiro' => 'February',
        'Marco' => 'March',
        'Abril' => 'April',
        'Maio' => 'May',
        'Junho' => 'June',
        'Julho' => 'July',
        'Agosto' => 'August',
        'Novembro' => 'November',
        'Setembro' => 'September',
        'Outubro' => 'October',
        'Dezembro' => 'December'
    ];

$string = str_replace(array_keys($month), array_values($month), $string);

$dr= date_create_from_format('d M Y', $string);
echo $dr->format('Y-m-d');

1

date('Y-m-d', strtodate($string));
  • I would like to know the reason for the negative marking, I was not clear enough ?

Browser other questions tagged

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