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

16,300

Solution 1

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

Solution 2

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

Share:
16,300
skyhigh
Author by

skyhigh

Updated on June 13, 2022

Comments

  • skyhigh
    skyhigh almost 2 years

    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.