[PHP]日期時間轉換

取得今天日期

$today = date('Y-m-d');
echo $today.PHP_EOL;

取得今天日期 ( 時分秒 )

$now = date('Y-m-d H:i:s');
echo $now.PHP_EOL;

取得明天日期

$tomorrow = date('Y-m-d',strtotime('+1day'));
echo $tomorrow.PHP_EOL;

加1年1月1日後的日期

$someday= date('Y-m-d',strtotime('+1year +1month +1day'));
echo $someday.PHP_EOL;

也可以加年月日等計算

+1year:年
+1month:月
+1week:週
+1day:天
+1hour:小時
+1minute:分鐘
+1second:秒

特定時間計算

$date = "2019-01-01"; //特定時間
$newdate = date('Y-m-d',strtotime("$date +1month"));
echo $newdate.PHP_EOL;

Y-m-d 參數請參考PHP手冊:https://www.php.net/manual/en/function.date.php

[PHP]計算2個日期之間有幾天

物件( Object oriented style ):

<?php
$datetime1 = new DateTime('2019-01-01');
$datetime2 = new DateTime('2019-01-31');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

// +30 days

程序式 ( Procedural style ) :

<?php
$datetime1 = date_create('2019-01-01');
$datetime2 = date_create('2019-01-31');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>
// +30 days

$interval->format 輸出格式說明:https://www.php.net/manual/en/dateinterval.format.php

透過迴圈來跑2個日期之間

$fristday = '2019-01-01';
$lastday = '2019-01-31';
$datetime1 = date_create($fristday);
$datetime2 = date_create($lastday);
$interval = date_diff($datetime1, $datetime2);
$godays = $interval->format('%a');
for ($i = 0; $i <= $godays; $i++) {
     $theday = date("Y-m-d",strtotime($fristday." +$i day")); 
     echo $theday.PHP_EOL;
 } 

輸出結果如下:

 2019-01-01
 2019-01-02
 2019-01-03
 2019-01-04
 2019-01-05
 2019-01-06
 2019-01-07
 2019-01-08
 2019-01-09
 2019-01-10
 2019-01-11
 2019-01-12
 2019-01-13
 2019-01-14
 2019-01-15
 2019-01-16
 2019-01-17
 2019-01-18
 2019-01-19
 2019-01-20
 2019-01-21
 2019-01-22
 2019-01-23
 2019-01-24
 2019-01-25
 2019-01-26
 2019-01-27
 2019-01-28
 2019-01-29
 2019-01-30
 2019-01-31