PHP: Convert date format
P粉769413355
P粉769413355 2023-08-27 13:34:57
0
2
547
<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>
P粉769413355
P粉769413355

reply all(2)
P粉439804514

The easiest way is

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('m/d/Y');

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:

$now = new DateTime();
$timestring = $now->format('Y-m-d h:i:s');

Another question also covers the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.

P粉006977956

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 the date() 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:

$old_date = date('l, F d y h:i:s');              // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template