Heim  >  Artikel  >  Backend-Entwicklung  >  php日期,时间有关知识整理

php日期,时间有关知识整理

WBOY
WBOYOriginal
2016-06-13 12:27:40855Durchsuche

php日期,时间相关知识整理

unix 时间戳:从1970年1月1日0点开始到当前时间所经过的秒数。

1.将日期转换为UNIX时间戳
mktime():可以自动校正越界的输入

原型 : mktime(hour,minute,second,month,day,year);
实例:

<?php    echo date("Y-m-d",mktime(0,0,0,2,12,2015));   //2015-12-12    echo date("Y-m-d h:i:s",mktime(7,50,59,10,21,2015)); //2015-10-21 07:50:59    echo date("Y-m-d",mktime(0,0,0,12,33,2015));   //2016-01-02 ,日期超过31天,自动校正时间?>

2.将英文文本的日期时间解析为unix时间戳
strtotime()
原型 :strtotime(time,now)

<?php    echo strtotime("now");   //1447987573    echo date("Y-m-d",strtotime("now"));   //2015-11-20    echo date("Y-m-d h:i:s",strtotime("now"));   //2015-11-20 02:49:18    echo date("Y-m-d",strtotime("8 december 2015"));   //2015-12-08?>

实例:通过strtotime()编写一个纪念日的倒计时程序

<?php            $now = strtotime("now");  //开始时间	$endTime = strtotime('2018-10-12 10:20:59');  //毕业时间,转成时间戳		$second = $endTime - $now;   //获取从毕业到现在的时间戳(秒数)	$year = floor($second/3600/24/365);  //从这个时间戳中算出的年数   floor() 函数向下舍入为最接近的整数。		$temp = $second - $year*365*24*3600;  //从时间戳中去掉整年的秒数,就剩下月份的秒数	$month = floor($temp/3600/24/30);  //换算出月数		$temp = $temp - $month*30*24*3600;  //减去整月的秒数,剩下天数的秒数	$day = floor($temp/3600/24);  //换算出剩余的天数	$temp = $temp - $day*24*3600;  //减去整天的秒数,剩下小时的秒数	$hour = floor($temp/3600);  //换算出剩余的小时数	$temp = $temp - $hour*3600;  //减去整小时的秒数,剩下分的秒数	$minute = floor($temp/60);  //换算出剩余的分数	$second1 = $temp - $minute*60;   //剩余的秒数	echo "距离毕业还有{$year}年{$month}月{$day}天{$hour}小时{$minute}分{$second1}秒";  //距离毕业还有2年10月27天1小时56分14秒?>

扩展 : 日期的计算
计算两个日期之间相隔的长度,最简单的方法就是通过计算两个UNIX时间戳只差。
实例 : 在php脚本中接收来自html表单提交的出生日期,来计算这个用户的年龄

<?php        $year = 1989;	$month = 12;	$day = 20;	$birthday = mktime(0,0,0,$month,$day,$year);   //转换成时间戳	$nowDay = strtotime("now");  //获取到当前日期时间戳	$ageUnix = $nowDay - $birthday;	$age = floor($ageUnix/(60*60*24*365));	echo "年龄:$age";   // 年龄:25?>

日期和时间格式化输出
当日期和时间需要保存或计算时,使用UNIX时间戳作为标准格式。
缺点 : unix时间戳格式可读性差
解决办法:调用date()格式化本地时间和日期
语法 date(format,timestamp) 格式化一个本地时间和日期

<?php            date_default_timezone_set('PRC'); //设置中国时区 	echo date("Y年-m月-d日 H:i:s");   //2015年-11月-20日 17:30:21    ?>

---------------------------------

说明 :学习笔记

参考资料 :《细说PHP》

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn