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));
Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.