How to convert a date array that was returned from parse_date back to a date string

I have a date array in a format that is returned by the date_parse PHP routine. I need to convert this date array to a date string.

I am looking for a function that does the inverse of date_parse. This is a function that takes a date array as a parameter and returns a date string.

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

An array of dates sometimes only has values ​​for "year," "month," and "day." In other cases, it will have the values ​​"year", "month", "day", "hour", "minute" and "second". If the hour, minute and second are missing, I expect the procedure to return a date string from 00:00:00 for the hour, minute, and second part of the string.

I spent some time searching, but still have not found a function opposite to date_parse.

+4
source share
3 answers

I was looking for the answer to the same question, but could not 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 Ymd H:i:s $date_string = date('Ymd 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 zeros you want if the hour, minute and second are not passed to mktime() .

+5
source

Well, the best I could find was just to use sprintf ... mktime needs to set the locale for the time, and I also don't like going through the timestamp to format the date.

So just print the formatted fields:

 // Parse from YYYY-MM-DD to associative array $date = date_parse_from_format("Ymd", "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 only the last 2 digits of the year (for example, from 1984 to "84").

0
source

I use date picker on 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 this array object to a date is as follows:

 $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 yours.

And the output of the date object:

 2016-04-26 17:54:00 

Link: What is the best way to convert CakePHP date picker form data into a PHP DateTime object?

0
source

All Articles