8
votes

I have a date array in the format which is returned by the php routine date_parse. I need to convert this date array back into a date string.

I am looking for a function which does the reverse of the date_parse routine. That is a function which will accept the date array as a parameter and will return a date string.

http://php.net/manual/en/function.date-parse.php

The date array I have will sometimes have only values for 'year', 'month', and 'day'. Other times it will have values for 'year', 'month', 'day', 'hour', 'minute', and 'second'. If the hour, minute and second values are missing I would expect that the routine would return a date string with 00:00:00 for the hour, minute, and second part of the string.

I have spent some time searching, but so far have not found a function that is the reverse of date_parse.

3

3 Answers

7
votes

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().

1
votes

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 zeros
echo 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").

0
votes

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?