Thursday, 9 August 2018

PHP: Convert YYYY-MM-DD To DD-MM-YYYY

OK, so you have a YYYY-MM-DD date format such as 2015-08-10. Now obviously, the YYYY-MM-DD format is more suited for software systems and databases than it is for end-users, which means that it is your task to convert it into a format that is a little more human-friendly.
The first approach is pretty simple. We convert it into a UNIX timestamp using the function strtotime before converting it into 10-08-2015 using the date function:
As you can see, the process is extremely simple. Once we have converted the string into a UNIX timestamp, we are able to convert it into any kind of date format that we want to.
Some people prefer using PHP’s DateTime object, simply because it’s powerful and it allows you to work with dates using OOP:
Lastly, you can completely avoid PHP’s date functions by:
  1. Exploding the string into an array by using the explode function.
  2. Reverse the order of the resulting array by using PHP’s inbuilt array_reverse function.
  3. Convert the array back into a string by using the implode function.
Personally, I think that you’d be crazy to use this approach. Still, it was worth highlighting.

0 comments:

Post a Comment