I had a case where I needed to convert time from the format of the US centric dd/MM/YYYY to something a little more sane.
A Very Bad (and Stupid) Way
Since I was starting from a set position of 18/07/2017
(for example), the first idea I had was to use explode
to do this:
$date = "18/07/2017"; $datearray = explode("/", $date); $newdate = $date[1].'-'.$date[0].'-'.$date[2]
I did say this was stupid, right? The reason I’d want to do that, though, is that gets it into a DD-MM-YYYY format, which can be parsed a little more easily. Unless you’re an American. Which means this idea is useless.
A Less Bad, But Still Bad, Way
What about making it unix timestamp?
$date = "18/07/2017"; $date_parse = date_parse_from_format( 'm/d/Y' , $date); $date_echo = mktime( $date_parse['hour'], $date_parse['minute'], $date_parse['second'], $date_parse['month'], $date_parse['day'], $date_parse['year'] );
Now I have a unix timestamp, which I can output any which way I want! At this point, if I’m not sure what version of PHP people are using, as long as it’s above 5.2, my code will work. Awesome.
But we can do better.
A Clever Way
Instead of all that, I could use date_parse_from_format
:
$date = "18/07/2017"; $date_parse = date_create_from_format('m/j/Y', $date ); $date_echo[] = date_format($date_parse, 'F d, Y');
And this will convert “18/07/2017” into “18 July, 2017”
Which is far, far more understandable.
So Which Is Best?
If it’s your own code on your own server, I’d use date_create_from_format
to control the output as you want.
If this is code you want to run on any server, like in a WordPress plugin, use the unix timestamp, and then use date_i18n
to localize:
date_i18n( get_option( 'date_format' ), $date_echo );