这里面有坑

if(time()>time('2016-7-14')) # 这个判断死活不正常.
$t=mktime('2016-7-13'); # 这个$t是一个巨大的数, 比time()大多了, 原因是, 参数传错了.
$t3=mktime(0,0,0,7,15,2016); # 这个格式就对了, 时分秒, 月日年, 这格式真心醉了.
$t2=strtotime('2016-7-13'); # 这个函数就可以这样传参数了. 年月日
---------------------正确的写法----------------------
if(time()>mktime(0,0,0,7,15,2016)) #2016年7月15日凌晨生效.

时间戳

  1. 比如 1980-10-1, 时间戳是: 339206400.
  2. 1980-10-2, 时间戳: 339292800
  3. 他们的差距就是一天: __86400__秒=60X60X24
  4. 1980-10-1, 转成天为单位: 339206400/86400=3926
  5. 1980-10-2, 转成天为单位: 3927, 正好和10月1日差1
  6. 注意这种算日子的算法, 必须把时区算成标准的__utc__: date_default_timezone_set(“utc”);

得到当天的整日子时间戳

$timestamp = strtotime('today midnight');
$today_at_midnight = strtotime(date("Ymd"));
$stamp = mktime(0, 0, 0);
$today = (new DateTime())->setTime(0,0);

灵活的strtotime

$a=strtotime("2 October 2018");
$b=strtotime('11/2/2016');
$t2=strtotime('2016-7-13');
echo date('d-m-Y H:i:s', strtotime('today', 1324189035));
echo date('d-m-Y H:i:s', strtotime('midnight', 1324189035));
//上面两句话是一样的, 都是半夜0:0:0的时间戳.

使用日期作为key

比如: 19801102 代表1980年11月2日.

从字符到时间戳(秒级)

strtotime('20160831'); //这个地方支持几乎无限的格式. :http://php.net/manual/zh/datetime.formats.php
mktime(1, 2, 3, 4, 5, 2006);// 2006-04-05T01:02:03+00:00, 用这个我疯了. 他还有个兄弟: gmmktime, 貌似他兄弟就是我要的.

从时间戳到字符(秒级)

date('Ymd', strtotime('20160831')); //这个好. 他的格林威治兄弟: gmdate, 一根筋兄弟: idate.
strftime('%Y%m%d', strtotime('20160831')); //这个是老式的.

从时间戳/字符到数组

getdate(strtotime('20160831'));
strptime();

dateinterval

我快疯了. 这个的构造函数的介绍, 官网上语焉不详.

我们使用构造函数实例化DateInterval实例,DateInterval构造函数的参数是一个表示时间间隔约定的字符串,这个时间间隔约定以字母__P__开头,后面跟着一个整数,最后是一个周期标识符,限定前面的整数。有效周期标识符如下:
Y(年)
M(月)
D(日)
W(周)
H(时)
M(分)
S(秒)
间隔约定中既可以有时间也可以有日期,如果有时间需要在日期和时间之间加上字母__T__,例如,间隔约定P2D表示间隔两天,间隔约定P2DT5H2M表示间隔两天五小时两分钟。

英文原文: The format starts with the letter P, for “period.” Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

吐槽一下php官网, 啥情况啊, 为啥中文不翻译呢? 网上的翻译还是很多的啊.

一段时间中的每一天

至少有3个方法:

  1. 使用dateinterval

    $daterange = new DatePeriod(new DateTime( '2012-08-01' ), new DateInterval('P1D') ,new DateTime( '2012-08-31' ));//起始时间, 时间间隔, 终止时间.
    foreach($daterange as $date){
        echo $date->format("Ymd") . "<br>\n";
    } //打印出8月1日到8月30日. 30个元素, 不包含31日.
    

  2. 使用86400

    for ($i = strtotime('2016-01-01'); $i < strtotime('2016-1-10'); $i += 86400) {
        print date("Ymd",$i) . '<br/>'."\n";
    }//打印出1日到九日, 9个元素, 不含10日. //这个做法也可以先除86400, 但是那样就有时区问题了.
    
    //86400还有另一个办法. 使用国际标准时间: gmmktime和gmdate
    $s='20160820';	
    $d=gmmktime(0,0,0,substr($s,4,2),substr($s,6,2),substr($s,0,4))/86400;
    $tend=$d+10; //初始化400天的库存.
    for($i=$d;$i<$tend;$i++){
    	echo gmdate("Ymd",$i*86400);
    }//20日到29日, 10天的数据, 不含30日
    

  3. 使用date

    for($i=0; $i<4; $i++){
    	print date("Ymd",strtotime("20160101 + $i day"));
    }打印了1日到4日, 4个元素.
    

时区

GMT/UTC 国际标准时区.

参考:

http://www.111cn.net/phper/php-cy/111483.htm