一篇好文:
官方解释: https://www.php.net/manual/en/function.date.php
1 <?php 2 3 class Login 4 { 5 /** 6 * event info 7 * @var dynamic object 8 * https://krisjordan.com/blog/2008/11/27/dynamic-properties-in-php-with-stdclass 9 */ 10 public $event; 11 private $timezone; 12 private $timezoneUTC; 13 14 public function __construct() { 15 $this->timezone = new DateTimeZone("Asia/Shanghai"); 16 $this->timezoneUTC = new DateTimeZone("UTC"); 17 $this->initEvent(); 18 } 19 public function initEvent() 20 { 21 $this->event= new stdClass(); 22 $startDate = "2021-03-01 00:00:00"; 23 $endDate = "2021-03-31 23:59:59"; 24 $this->event->startDate = new DateTime($startDate, $this->timezone); 25 $this->event->endDate = new DateTime($endDate, $this->timezone); 26 return true; 27 } 28 29 public function index($request) 30 { 31 $post = isset($request->post) ? $request->post : []; 32 33 //@TODO 业务代码 34 $now = new DateTime("now", $this->timezone); 35 $diff = $this->event->startDate->diff($now); //8 days 36 $eventStartStr = date_format($this->event->startDate, 'Y-m-d H:i:sP'); //2021-03-01 00:00:00+08:00 37 $nowStr = date_format($now, 'Y-m-d H:i:sP'); //2021-03-09 09:07:22+08:00 38 39 //change to UTC timezone 40 //https://stackoverflow.com/questions/29019927/php-cant-set-correct-datetimezone-to-datetime 41 //$nowUTC = $now->setTimeZone($this->timezoneUTC); 42 43 $res = array("now" => $now, "nowStr" => $nowStr, "eventStart" => $this->event->startDate, "evenStartStr" => $eventStartStr, "diff" => $diff); 44 return json_encode($res); 45 } 46 }
1 { 2 "now": { 3 "date": "2021-03-11 16:39:05.965319", 4 "timezone_type": 3, 5 "timezone": "Asia/Shanghai" 6 }, 7 "nowStr": "2021-03-11 16:39:05+08:00", 8 "eventStart": { 9 "date": "2021-03-01 00:00:00.000000", 10 "timezone_type": 3, 11 "timezone": "Asia/Shanghai" 12 }, 13 "evenStartStr": "2021-03-01 00:00:00+08:00", 14 "diff": { 15 "y": 0, 16 "m": 0, 17 "d": 10, 18 "h": 16, 19 "i": 39, 20 "s": 5, 21 "f": 0.965319, 22 "weekday": 0, 23 "weekday_behavior": 0, 24 "first_last_day_of": 0, 25 "invert": 0, 26 "days": 10, 27 "special_type": 0, 28 "special_amount": 0, 29 "have_weekday_relative": 0, 30 "have_special_relative": 0 31 } 32 }