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

Asked

Viewed 57 times

-3

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

Is there a function I can use?

2 answers

4

  • 1

    I don’t think it applies to what I said, but I would have deleted it anyway. If I had posted directed to someone, it still will. Too bad I can’t restore the comment, or I’d even put it back in the community evaluate, because in my understanding, there was no sarcasm. There are 2 negative votes that may have been user tantrum or PHP ignorance (which is very common here). And I invited to suggest improvements. But the vote is free and I am the first to defend it. Note that I never said the person should review the vote, as many users do.

  • It’s the least I expect from those who will vote, after all, the question is PHP right? If you are going to vote because you are a friend of this or that user, then it is not a valid criterion (despite having a lot that seems to be club, it is up to moderation to check). Noting that my comments were made considering that there are 5 negatives in 3 responses, it was not the fact that they gave a -1 in my reply. You may have a real reason, but you’re a little off the mark.

3



Using the function 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 on IDEONE.

Handbook:

http://php.net/manual/en/function.date-parse-from-format.php


Using the class DateTime::createFromFormat

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

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

See working on IDEONE.

Handbook:

http://www.php.net/manual/en/datetime.createfromformat.php


Using the function preg_match

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

See working on IDEONE.

Handbook:

http://www.php.net/manual/en/function.preg-match.php

Browser other questions tagged

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