How to Convert String to Date and Date-Time in PHP
To convert a string to Date
and DateTime
, several functions or methods can be used, like the combination of strtotime()
and date()
, using the DateTime::createFromFormat
class method or format()
method within the same class, or the PHP built-in function of date_create_from_format
.
Combination of strtotime()
and date
The strtotime()
function returns the number of seconds passed from January 01, 1970, just like a Linux machine timestamp. It returns the total seconds from the provided parameter passed to the function.
Parameters:
Time/Date
(required) - This parameter specifies the date/time with string format.Now
(optional) - This parameter is the timestamp that can be used as a base on the calculation of relative dates
The date()
function is the one that formats the local date and time, and return a new formatted date string.
Parameters:
format
(required) - This parameter specifies the format of the provided string.timestamp
(optional) - This parameter is an integer UNIX timestamp and the default value is the current local time.
To properly use both strtotime()
and date()
, use strtotime()
on the first date and then use date()
to convert it back.
Example:
$oldDate = strtotime('03/08/2020');
$newDate = date('Y-m-d',$time);
echo $newDate;
//output: 2020-03-08
Note: There’s a huge difference between /
and -
when using as a divider on formatting a date, if the separator is a /
then the American format m/d/y
is assumed; and if the divider is a -
, then the European d-m-y
format is assumed. To avoid ambiguity, it is recommended to use ISO 8601 (YYYY-MM-DD)
dates.
Use DateTime::createFromFormat
or date_create_from_format
The DateTime::createFromFormat
is a built-in PHP function that returns a new DateTime
object that represents the date and time format. On the other hand, date_create_from_format
is a procedural style using the DateTime::createFromFormat
.
Parameters:
Format
(required) - This parameter specifies what format to use.Time
(required) - This parameter represents date/time string. If this parameter is NULL, then it will use the current date/time.Timezone
(optional) - The time zone of time. The default value is the current time zone.
Example of DateTime::createFromFormat
echo $dateNew = DateTime::createFromFormat('m-d-Y', '03-08-2020')->format('Y/m/d');
//output: 2020/03/08
Example of date_create_from_format
echo $dateNew = date_create_from_format("m-d-Y", "03-08-2020")->format("Y-m-d");
//output: 2020/03/08
The only difference between date_create_from_format
and DateTime::createFromFormat
is that the DateTime::createFromFormat
is not available in PHP 5.2 and below.
Related Article - PHP Date
- How to Add Days to Date in PHP
- How to Calculate the Difference Between Two Dates Using PHP
- How to Convert DateTime to String in PHP
- How to Convert One Date Format to Another in PHP
- How to Get the Current Date and Time in PHP