Home >Backend Development >PHP Tutorial >How to convert string to Date and DateTime in PHP
#Convert string to Date and DateTime using several functions/methods, such as strtotime(), getDate(). Let's take a look at what these functions do.
strtotime() function , returns the number of seconds elapsed since January 1, 1970, just like a Linux machine timestamp. It returns the number of seconds passed as arguments passed to the function.
Syntax
strtotime(parameter);
Parameters: Time/Date, now (optional)
Returns the number of seconds that have passed since January 1, 1970.
getDate() function, returns the date/time information of the passed parameter (date/time);
Syntax
getDate(parameter);
This parameter is optional , because it takes the current local time as the default parameter.
It returns the date, date, year, month and other information in the array.
1. Code to convert string to Date date:
<?php $time_input = strtotime("2019/01/29"); $date_input = getDate($time_input); print_r($date_input); ?>
Output:
Array ( [seconds] => 0 [minutes] => 0 [hours] => 0 [mday] => 29 [wday] => 2 [mon] => 1 [year] => 2019 [yday] => 28 [weekday] => Tuesday [month] => January [0] => 1548720000 )
2. Convert character Code for converting string to dateTime
<?php $input = '01/29/2019 19:00:02'; $date = strtotime($input); echo date('d/M/Y h:i:s', $date);
Output:
29/Jan/2019 07:00:02
Note 1: We can use "D" in the position of "d" to get the output The date of
<?php $input = '01/29/2019 15:00:02'; $date = strtotime($input); echo date('D/M/Y h:i:s', $date);
Output:
Tue/Jan/2019 03:00:02
Note 2: We can use "H" in the position of "h" to get the time in 24-hour format in the output
<?php $input = '01/29/2019 14:00:02'; $date = strtotime($input); echo date('D/M/Y H:i:s', $date);
Output:
Tue/Jan/2019 14:00:02
Similarly, the "i" and "s" can also be changed to uppercase to find a different output, but that's not of much use.
The above is the detailed content of How to convert string to Date and DateTime in PHP. For more information, please follow other related articles on the PHP Chinese website!