在PHP编程中经常需要对时间进行处理,在不同的情况下,为了方便阅读会显示不同的时间格式,或者计算两个日期节点之间的时间差等。
可以使用date()函数对获取的时间进行格式化处理,语法如下:
string date ( string $format [, int $timestamp ] )
该函数返回将整数timestamp按照给定的格式字符串而产生的字符串,如果没有给出时间戳就使用本地时间。格式化字符串中可以识别的format参数如表7-2所示。
表7-2 date()函数可识别的format参数
下面用一个例子演示date()函数以不同的时间格式输出当前时间:
<? // 设定要用的时区 date_default_timezone_set('PRC'); // 输出类似Monday echo date("l"); echo "<br/>"; // 输出类似Monday 15th of August 2005 03:12:46 PM echo date('l dS \of F Y h:i:s A'); echo "<br/>"; // 输出July 1, 2000 is on a Saturday echo "July 1, 2000 is on a " . date("l"); echo "<br/>"; /* 在格式参数中使用常量 */ // 输出类似Wed, 25 Sep 2013 15:28:57 -0700 echo date(DATE_RFC2822); echo "<br/>"; // 输出类似2000-07-01T00:00:00+00:00 echo date(DATE_ATOM); echo "<br/>"; //输出类似2000-07-01 14:00:00 echo date('Y-m-d H:i:s'); ?>
执行以上程序的输出结果如下:
Sunday Sunday 10th of July 2016 03:46:01 PM July 1, 2000 is on a Sunday Sun, 10 Jul 2016 15:46:01 +0800 2016-07-10T15:46:01+08:00 2016-07-10 15:46:01
假如想知道用户最后登录网站距离现在已经过去了多长时间,这时就要计算两个日期间相差多长时间。
计算日期时间差需要先把两个日期转换成纪元时间戳再计算。示例如下:
<?php //2016年1月1日19点30分0秒 $start = mktime(19,30,0,1,1,2016); //2016年7月7日7点30分0秒 $end = mktime(7,30,0,7,7,2016); $diff_seconds = $end - $start; //一周的秒数是 24*60*60=604800 秒 $diff_weeks = floor($diff_seconds/604800); //一天的描述是 24*60*60=86400 $diff_days = floor($diff_seconds/86400); $diff_hours = floor($diff_seconds/3600); $diff_minutes = floor($diff_seconds/60); echo "2016年1月1日19点30分0秒和2016年7月7日7点30分0秒之间相差 $diff_seconds 秒,$diff_weeks 个星期,$diff_days 天,$diff_hours 个小时,$diff_minutes 分钟"; ?>
执行以上程序的输出结果为:
2016年1月1日19点30分0秒和2016年7月7日7点30分0秒之间相差 16200000 秒,26 个星期,187 天,4500 个小时,270000 分钟
在PHP中还经常使用到strtotime()函数。这个函数可将任何英文文本的日期时间描述解析为UNIX时间戳,语法如下:
int strtotime ( string $time [, int $now = time() ] )
说明:该函数执行成功,则返回时间戳,否则返回false。
strtotime()函数的使用示例如下:
<?php echo strtotime("now"), "\n"; echo strtotime("10 September 2000"), "\n"; echo strtotime("+1 day"), "\n"; echo strtotime("+1 week"), "\n"; echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n"; echo strtotime("next Thursday"), "\n"; echo strtotime("last Monday"), "\n"; ?>
执行以上程序打印出来的结果类似:
1468137722 1473465600 1468224122 1468742522 1468929724 1468454400 1467590400
有时我们需要在一个日期上加减一定的时间间隔。可以使用strtotime()来计算一些日期时间间隔。示例如下:
<?php $start = 'last Monday'; $interval = strtotime("$start + 4 days"); echo "现在\$interval 表示上周的" . date('l',$interval); ?>
执行以上程序的输出结果为:现在$interval表示上周的Friday。
如果日期使用时间戳表示,并且时间间隔也可用秒来表示,就可以从时间戳中减去时间间隔。示例如下;
<?php $start = time(); echo date('Y-m-d',$start); $interval = 7 * 24 * 3600; // 一周 $end = $start - $interval; echo date('Y-m-d',$end); ?>
执行以上程序的输出结果为:
2016-07-10 2016-07-03
前后两个日期正好相差7天。