当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP教程:时间函数

PHP
使用 PHP 和 Oracle 开发企业应用程序
可扩展 可伸缩的 Oracle 与 PHP
Andi Gutmans看 PHP 5、Oracle 的未来
PEAR版本号说明
PEAR的安装
PHP 新手总结的 PHP 基础知识
WAP 与 PHP 程序设计之基础篇
PHP强制对象类型之instanceof操作符(1)
PHP强制对象类型之instanceof操作符(2)
PHP强制对象类型之instanceof操作符(3)
Linux平台wacom产品使用指南
一个嵌入式Linux系统的键盘驱动实现 (1)(2)
一个嵌入式Linux系统的键盘驱动实现 (1)
SWT的可视化控件的X11窗口句柄简介
Linux系统内核中的Device Mapper机制 (1)(5)
Linux系统内核中的Device Mapper机制 (1)(4)
Linux系统内核中的Device Mapper机制 (1)(3)
Linux系统内核中的Device Mapper机制 (1)(2)
Linux系统内核中的Device Mapper机制 (1)
又一关于apache和mysql组合的问题 - PHPchina

PHP教程:时间函数


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 58 ::
收藏到网摘: n/a

PHP中的日期时间基本上基于UNIX时间戳来处理的。
比如date/getdate()/mktime()/strftime()/strtotime/time等都与时间戳有着密切的关联。
这些函数的用法可查阅相关文档,这里就不对这些函数作解释了。
要将时间戳转为可读的形式,就需要date函数出马了,他需要二个参数:格式化字符串与时间戳。
比较难记的是格式化字符,不过常用的也就是YymdwHis,其它的亦可参阅文档。

将可读的日期转为时间戳通常用以下二个函数:
mktime
如:
$timestam = mktime(18,30,00,8,10,1981);
将得到1981年8月10日下午6点30整的时间戳。
另一个比较NB的是strtotime,看名字就是将字符串转为一个时间戳。
它的NB之处不在于解析如:Tue,15 Mar 2005 15:23:52或2008-01-01此类的字符串,strtotime还可以“理解”一定的英语。
如下面的代码:

<?php
date_default_timezone_set("PRC");
$mydatestring = array('now','today','tomorrow','yesterday','thursday','this thursday','last thursday','+2 hours','-1 month','30 seconds','next week','last year','2 weeks ago');
foreach($mydatestring as $item)
{
echo "$item:".date('r',strtotime($item)).'<br />';
}
?>

输出:

now:Sat, 28 Feb 2009 11:03:35 +0800
today:Sat, 28 Feb 2009 00:00:00 +0800
tomorrow:Sun, 01 Mar 2009 00:00:00 +0800
yesterday:Fri, 27 Feb 2009 00:00:00 +0800
thursday:Thu, 05 Mar 2009 00:00:00 +0800
this thursday:Thu, 05 Mar 2009 00:00:00 +0800
last thursday:Thu, 26 Feb 2009 00:00:00 +0800
+2 hours:Sat, 28 Feb 2009 13:03:35 +0800
-1 month:Wed, 28 Jan 2009 11:03:35 +0800
30 seconds:Sat, 28 Feb 2009 11:04:05 +0800
next week:Sat, 07 Mar 2009 11:03:35 +0800
last year:Thu, 28 Feb 2008 11:03:35 +0800
2 weeks ago:Sat, 14 Feb 2009 11:03:35 +0800

 

再如我要查找下个月的第一个星期五:

$nextmonth = date('Y-'.(date('n')+1).'-0');
$nextmonth_timest = strtotime($nextmonth);
$first_fri = strtotime('Fri',$nextmonth_timest);
echo "Today:".date('Y-m-d');
echo '<br />';
echo 'the first Fri of next month is :'.date('Y-m-d',$first_fri);

 

输出:
Today:2009-02-28
the first Fri of next month is :2009-03-06

还有太多太多,以后有时间再写。