下面是这几个类的具体使用例子:
<?php function 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:00 showTimeObj('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
PS:这里再为大家推荐几款时间及日期相关工具供大家参考:
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php日期与时间用法总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php面向对象程序设计入门教程》及《php字符串(string)用法总结》