<?phpfunction showTimeObj($msg,$timeObj){ //使用预定义的格式来转换时间字符串 if ($msg!=NULL) { echo $msg.":"; echo "<br>".$timeObj->format(DATE_W3C)."<br>"; } else { echo $timeObj->format(DATE_ATOM)."<br>"; }}try{ //设置时区 $timezones = new DateTimeZone('Asia/Shanghai'); //获取当前时间 $timeObj=new DateTime("now",$timezones);}catch (Exception $e){ echo $e->getMessage();}//输出的+08:00代表东八区、若把时区设为'Asia/Tokyo',则为+09:00showTimeObj('current time',$timeObj);echo "<br>"."<br>";echo "use DateInterval object to add date time".":"."<br>";//加上一天(P=period,必备)$timeObj->add(new DateInterval('P1D'));showTimeObj('current time + 1 day',$timeObj);//加上一小时(T=time,可选)$timeObj->add(new DateInterval('P0DT1H'));showTimeObj('current time + 1 day & 1hour',$timeObj);echo "<br>"."<br>";echo "use DatePeriod to process time range like a iterator".":"."<br>";//DatePeriod: 迭代处理区间内的日期$interval= new DateInterval('P0DT2H');$start = new DateTime('2018-08-08',$timezones);$end = new DateTime('2018-08-09',$timezones);$timeRange = new DatePeriod($start,$interval,$end);foreach ($timeRange as $hour){ showTimeObj(NULL,$hour);}?>
current time:
2018-09-04T15:23:46+08:00
use DateInterval object to add date time:
current time + 1 day:
2018-09-05T15:23:46+08:00
current time + 1 day & 1hour:
2018-09-05T16:23:46+08:00
use DatePeriod to process time range like a iterator:
2018-08-08T00:00:00+08:00
2018-08-08T02:00:00+08:00
2018-08-08T04:00:00+08:00
2018-08-08T06:00:00+08:00
2018-08-08T08:00:00+08:00
2018-08-08T10:00:00+08:00
2018-08-08T12:00:00+08:00
2018-08-08T14:00:00+08:00
2018-08-08T16:00:00+08:00
2018-08-08T18:00:00+08:00
2018-08-08T20:00:00+08:00
2018-08-08T22:00:00+08:00