Home >Backend Development >PHP Tutorial >How to convert string to Date and DateTime in PHP

How to convert string to Date and DateTime in PHP

藏色散人
藏色散人Original
2019-01-29 14:39:1818838browse


#Convert string to Date and DateTime using several functions/methods, such as strtotime(), getDate(). Let's take a look at what these functions do.

How to convert string to Date and DateTime in PHP

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 = &#39;01/29/2019 19:00:02&#39;;
$date = strtotime($input);
echo date(&#39;d/M/Y h:i:s&#39;, $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 = &#39;01/29/2019 15:00:02&#39;;
$date = strtotime($input);
echo date(&#39;D/M/Y h:i:s&#39;, $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 = &#39;01/29/2019 14:00:02&#39;;
$date = strtotime($input);
echo date(&#39;D/M/Y H:i:s&#39;, $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn