Separate year/month

Asked

Viewed 66 times

2

I have the following date format:

201705

I’d like to put a / between the year and the month. How do I do it?

1 answer

4


If you’re working with dates, use DateTime::createFromFormat:

$date = DateTime::createFromFormat('Ym', '201705');
echo $date->format('Y/m');

See the example on ideone

If it’s just one string with this standard, you can use substr_replace:

echo substr_replace('201705','/', 4, 0);

See the example on ideone

  • 1

    Or echo preg_replace('/ d{4}/', '$0/', '201705');

  • You could give it as an alternative in a new answer, @Marcosxavier

  • Because it is very simple, I found it complementary here instead of an answer.

Browser other questions tagged

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