PHP: Convert date format
P粉769413355
2023-08-27 13:34:57
<p>Is there an easy way to convert one date format to another in PHP? </p>
<p>I have this:</p>
<pre class="brush:php;toolbar:false;">$old_date = date('y-m-d-h-i-s'); // works
$middle = strtotime($old_date); // returns bool(false)
$new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00</pre>
<p>But of course I want it to return the current date and not the time of day. What did i do wrong? </p>
The easiest way is
You first provide it with the format of $dateString. Then you tell it the format you want $newDateString to be in.
This also avoids using strtotime, which can sometimes be difficult to use.
If you don't intend to convert from one date format to another, but just want the current date (or datetime) in a specific format, then this is simpler:
Another question also covers the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.
The second argument to
date()
needs to be the correct timestamp (number of seconds since January 1, 1970). You are passing a string that date() doesn't recognize.You can use strtotime() to convert a date string to a timestamp. However, even strtotime() doesn't recognize the
y-m-d-h-i-s
format.PHP 5.3 and higher
Use
DateTime::createFromFormat
. It allows you to specify the exact mask - using thedate()
syntax - to parse the incoming string date.PHP 5.2 and lower versions
You must manually parse the elements (year, month, day, hour, minute, second) using
substr()
and pass the result to mktime() will build a timestamp for you.But this requires a lot of work! I recommend using a different format that strftime() understands. strftime() understands any entered date,
the next time Joe slips on the ice
. For example, this works: