Home  >  Article  >  Backend Development  >  How to get current time and date using php

How to get current time and date using php

不言
不言Original
2019-02-20 09:46:3025950browse

How to get the current time and date using How to get current time and date using php? In PHP, we can use the date() function to get the current time and date, or we can use the DateTime PHP class in PHP>5.2 to get the date and time. Let's take a look at the specific content.

How to get current time and date using php

Use the date() function to output the current date and time. It will use the default time zone configured in How to get current time and date using php.ini.

<?How to get current time and date using php
echo date(&#39;Y-m-d H:i:s&#39;);
?>

Use the date time() class to output the current date and time. It will also use the default time zone.

<?How to get current time and date using php
$datetime = new DateTime();
echo $datetime->format(&#39;Y-m-d H:i:s&#39;);
?>

Date and time in PHP time zone:

It is also possible to define a specific time zone for the application. Now PHP will not use the system defined time zone.

<?How to get current time and date using php
date_default_timezone_set(&#39;UTC&#39;);
 
$datetime = new DateTime();
echo $datetime->format(&#39;Y-m-d H:i:s&#39;);
?>

Convert Date Time Time Zone

For example, you have stored the date (2018-01-11 01:17:23) in UTC time zone in the database. Now convert this DateTime to EST time zone.

<?How to get current time and date using php
$date = new DateTime(&#39;2011-11-10 20:17:23&#39;, new DateTimeZone(&#39;UTC&#39;));
 
$date->setTimezone(new DateTimeZone(&#39;EST&#39;));
echo $date->format(&#39;Y-m-d H:i:s&#39;);
?>

After executing the above command, you will get the following results.

2018-01-11 01:17:23

This article ends here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to get current time and date using 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