How to convert a date array that was returned from date_parse back into a date string
I was looking for an answer to the same question but couldn't find it. I found some examples in the PHP documentation using date()
and mktime()
and came up with this...
$date_array = date_parse($date_string);// returns original date string assuming the format was Y-m-d H:i:s$date_string = date('Y-m-d H:i:s', mktime($date_array['hour'], $date_array['minute'], $date_array['second'], $date_array['month'], $date_array['day'], $date_array['year']));
I tested this and the string will contain the zeroes you want if the hour, minute and second are not passed to mktime()
.
Well, the best I could find is just to use sprintf
... mktime
requires time locale to be set, and I also don't like to go through a timestamp to format the date.
So, just print formatted fields:
// Parse from YYYY-MM-DD to associative array$date = date_parse_from_format("Y-m-d", "2014-07-15");// Write back to DD/MM/YYYY with leading zerosecho sprintf("%02d/%02d/%04d", $date["day"], $date["month"], $date["year"]);
EDIT: but this solution requires some tweaking if you need, for example, to print just the last 2 digits of a year (e.g. from 1984 to "84").
I use date picker in the form, and the return format is an array:
[start] => Array ( [month] => 04 [day] => 26 [year] => 2016 [hour] => 05 [min] => 54 [meridian] => pm ) [end] => Array ( [month] => 04 [day] => 26 [year] => 2016 [hour] => 05 [min] => 54 [meridian] => pm )
The way to convert that array to date object is as following:
$timeArray = $this->request->data['Task']['start'];$start = $this->Task->deconstruct('start', $timeArray);
My model is "Task" and the key for the date array is "start", you need to replace these two fields with your own.
And the output of the date object is:
2016-04-26 17:54:00
Reference: How best to convert CakePHP date picker form data to a PHP DateTime object?