Home  >  Article  >  Backend Development  >  Detailed explanation of common methods of php DateTime

Detailed explanation of common methods of php DateTime

怪我咯
怪我咯Original
2017-07-06 10:54:531681browse

This article organizes some methods used by DateTime objects to facilitate everyone's search and browsing. You can refer to them if necessary.

Preface

Placing \ in front of the instantiated object indicates that the native class is used in the namespace. If the namespace is not used, you can delete the previous \

1. Output the current time

$datetime = new \DateTime;
print_r($datetime->format('Y-m-d H:i:s'));

2. Output the given time

$datetime = new \DateTime('2016-06-13');
print_r($datetime);

3. Format the given time to the time you want

$datetime = \DateTime::createFromFormat('Ymd', '20160618');
print_r($datetime->format('Y-m-d'));

4. Output Unix timestamp format (method 1 will return a negative number if it is before 1990, and method 2 will return false)

//方法1(php5.2):
$datetime = new \DateTime();
echo $datetime->format('U');exit;

//方法2(php5.3)推荐
$datetime = new \DateTime();
echo $datetime->getTimestamp();exit;

5. Format to the given time based on the given timestamp

$datetime = new \DateTime();
$datetime->setTimestamp(1465783744);
echo $datetime->format('Y-m-d H:i:s');

6. Compare two dates and times, compare year to year, compare month to month...

$datetime1 = new \DateTime('2016-01-01 10:11:18');
$datetime2 = new \DateTime('2017-05-11 22:21:21');
$interval = $datetime1->diff($datetime2);
print_r($interval->format('%Y'));//%表示使用格式化,R表示是大于这个日期(+),还是小于这个日期(-),a表示大于或小于多少天,时分秒正常使用y,m,d,h,i,s

7. Create a time with a length of several days ago

DateInterval constructionThe parameter of the function is a string representing the time interval agreement. This time interval agreement starts with the letter P, followed by integer, and finally a period identifier qualifying the preceding integer. Valid period identifiers are as follows: Y (year) M (month) D (day) W (week) H (hour) M (minute) S (second) The interval agreement can have both time and date, if time is needed Add the letter T between the date and time. For example, the interval convention P2D means an interval of two days, and the interval convention P2DT5H2M means an interval of two days, five hours and two minutes.

$datetime = new \DateTime();
$interval = new \DateInterval('P2DT5H');
//或者使用createFromDateString方法
//$interval = \DateInterval::createFromDateString('1 month');
//修改DateTime实例
$datetime->add($interval);
echo $datetime->format('Y-m-d H:i:s');

8. Create the time a few days ago

$datetime = new \DateTime();
$interval = new \DateInterval('P2DT5H');
$datetime->sub($interval);
echo $datetime->format('Y-m-d H:i:s');
//ps:有个modify方法,这个方法是减去30,并不是像前推1天,输出的还是12月
$datetime = new \DateTime('2014/12/31');
$datetime->modify( '-1 month' );
print_r($datetime);exit;

9. Reset the time of the current DateTime object Different dates, pass year, month, day

$datetime = new \DateTime();
$datetime->setDate(2015, 2, 28);
echo $datetime->format('Y-m-d');exit;

10. Reset the time of the current DateTime object to different times, pass hours, minutes, seconds ( Optional parameters)

$datetime = new \DateTime();
$datetime->setTime(20, 20, 24);
echo $datetime->format('Y-m-d H:i:s');exit;

11. Change the time zone before formatting the time

$timezone = new \DateTimeZone('Asia/Calcutta');
$datetime = new \DateTime();
$datetime->setTimezone($timezone);
print_r($datetime->format('Y-m-d H:i:s'));exit;

12. Return the time zone

$date = new \DateTime(null, new DateTimeZone('Asia/Shanghai'));
$tz = $date->getTimezone();
echo $tz->getName();

13. Calculate the offset value of two time zones

$dateTimeZoneTaipei = new \DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new \DateTimeZone("Asia/Tokyo");
$dateTimeTaipei = new \DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new \DateTime("now", $dateTimeZoneJapan);
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);
print_r($timeOffset);exit;

14. Return the time interval, how long

$interval = new \DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');

15. Iterate and output the days before the current date.

Constructor method of DatePeriod classAccepts three parameters and must provide a DateTime instance, indicating the date and time when the iteration starts, and a DateInterval instance, indicating the next date The interval between it and time is an integer, indicating the total number of iterations. The fourth parameter is optional and is used to explicitly specify the end date and time of the cycle. If you want to exclude the start date and time when iterating, you can put the last part of the constructor One parameter is set to DatePeriod::EXCLUDE_START_DATEConstant:

$datetime = new \DateTime();
$interval = \DateInterval::createFromDateString('-1 day');
$period = new \DatePeriod($datetime, $interval, 3);
foreach ($period as $date) {
  echo $date->format('Y-m-d'), PHP_EOL;
}

The above is the detailed content of Detailed explanation of common methods of php DateTime. 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