本文实例讲述了PHP UNIX时间戳用法。分享给大家供大家参考,具体如下:
时间戳是文件属性中的创建、修改、和访问时间。数字时间戳服务是Web网站安全服务项目之一,能提供电子文件的日期和时间信息的安全保护。
时间戳的优点是:
可用变化的加密数值,防止数值被窃取后非法重复利用,起到加密的作用。时间戳主要依赖于时间,在约定的一段时间内产生唯一的一个数值。
UNIX时间戳
在UNIX系统中,日期与时间表示为自1970年1月1日零点起到当前时刻的秒数,这种时间被称为UNIX时间戳,以32位二进制数表示。在不同的操作系统中均支持这种时间表示方式,同一时间在UNIX和Windows中均以相同的UNIX时间戳表示,所以不需要在不同的系统中进行转换。
目前UNIX时间戳是以32位二进制数表示,32位二进制数值范围为(-2147483648~+2147483647),由于系统不支持负的时间戳,因此,目前UNIX时间戳能表示的最大时间为2038年1月19日3点14分7秒,该时刻的时间戳为2147483647。于该时间后,需要扩展UNIX时间戳的二进制位数。
PHP获取指定日期的时间戳
PHP中应用mktime()函数将一个时间转换成为UNIX时间戳值。
语法如下
mktime(hour,minute,second,month,day,year,is_dst)
PHP;">
echo "时间戳:".mktime().'
';//返回当前时间戳 echo "任意日期:".date("Y-m-d",mktime(0,2,21,1996)).'
'; echo "当前日期: ".date("Y-m-d",mktime()).'
'; @H_403_43@
';//返回当前时间戳 echo "任意日期:".date("Y-m-d",mktime(0,2,21,1996)).'
'; echo "当前日期: ".date("Y-m-d",mktime()).'
'; @H_403_43@
运行结果为:
PHP;">
时间戳:1458979695
任意日期:1996-02-21
当前日期: 2016-03-26
@H_403_43@
获取当前时间戳
语法如下:
int time(void);
该函数没有参数,返回值为UNIX时间戳的整数值。
例如:
PHP;">
echo time()."
";//输出当前时间戳 $nextWeek = time()+(7*24*60*60);//一个星期七天,一天24小时,一个小时60分,一分60秒 echo "Now: ".date("Y-m-d")."
"; echo "Next Week: ".date("Y-m-d",$nextWeek); @H_403_43@
";//输出当前时间戳 $nextWeek = time()+(7*24*60*60);//一个星期七天,一天24小时,一个小时60分,一分60秒 echo "Now: ".date("Y-m-d")."
"; echo "Next Week: ".date("Y-m-d",$nextWeek); @H_403_43@
运行结果为
PHP;">
1458980073
Now: 2016-03-26
Next Week: 2016-04-02
@H_403_43@
例如:
将英文文本的日期时间描述解析为UNIX时间戳
strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。
语法
strtotime(time,now)
PHP;">
echo(strtotime("now")).'
'; echo(strtotime("3 October 2005")).'
'; echo(strtotime("+5 hours")).'
'; echo(strtotime("+1 week")).'
'; echo(strtotime("+1 week 3 days 7 hours 5 seconds")).'
'; echo(strtotime("next Monday")).'
'; echo(strtotime("last Sunday")).'
'; @H_403_43@
'; echo(strtotime("3 October 2005")).'
'; echo(strtotime("+5 hours")).'
'; echo(strtotime("+1 week")).'
'; echo(strtotime("+1 week 3 days 7 hours 5 seconds")).'
'; echo(strtotime("next Monday")).'
'; echo(strtotime("last Sunday")).'
'; @H_403_43@
运行结果为:
PHP;">
1458980310
1128268800
1458998310
1459585110
1459869515
1459094400
1458403200
@H_403_43@
如果想要查看这个时间戳对应的时间,例如:
PHP;">
echo date("Y-m-d H:i:s",strtotime("now")).'
'; echo date("Y-m-d H:i:s",strtotime("next Thursday")).'
'; @H_403_43@
'; echo date("Y-m-d H:i:s",strtotime("next Thursday")).'
'; @H_403_43@
运行结果为: