P粉4398045142023-08-28 12:37:15
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粉0069779562023-08-28 09:51:45
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);