Jump to content

Convert YYYY to YYYYMMDD


blinks58

Recommended Posts

 

$date = date('Y0101', strtotime(2000));

But there is nothing wrong with what the above poster gave. Either will work fine.

Nothing wrong at all, except it will print the value for January 1st of the current year. When given to strtotime(), the 2000 is interpreted as a 24-hour time: 8pm.

 


I just thought there would be a "proper" way to do it, rather than what is effectively a hack.

A good way would be something like the following, which uses DateTime::createFromFormat().

 

$date = DateTime::createFromFormat('!Y', $year)->format('Ymd');

 

If you're still stuck on PHP 5.2 or lower (I'm sorry!) then mktime() is an alternative.

 

$date = date('Ymd', mktime(0, 0, 0, 1, 1, $year));

Thanks akphidelit2007. Yes, that is a simple solution. I just thought there would be a "proper" way to do it, rather than what is effectively a hack.

 

Your solution does work. Thank you.

How is it a "hack"?

 

You have a year as a string. You want to print that year plus "0101". Literally that is as simple as concatenating your two strings.

 

It's like if you said you had a last name and wanted to display the first name as "joe" for every last name.

echo "Joe ".$lastname;

 

 

 

If you want it in a format other than a STRING then you'll want to use fancier functions, but so far your post only indicated adding the string of "0101".

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.