问答 百科手机端

php常用时间日期函数

2023-03-14 15:54

一、获取时间戳

1、time() -- UTC时间戳,1970年1月1日零点以来的秒数。经实验不受php.ini中date.timezone的影响。

2、microtime() -- 返回类似"0.53294300 1584762409"的字符串,两部分的单位都是秒。前半部分为小数部分,数字上精确到小数点后6位,即微秒;后半部分为整数部分,同time()。

   microtime(true) -- 返回类似1584762409.5325的浮点数

3、mktime(hour,minute,second,month,day,year) --根据输入值得到时间戳
   本函数会受到电脑时区的影响。建议使用gmmktime()函数。

4、strtotime(时间表达或运算字符串) -- 返回时间戳

   举例:
   strtotime("2020-3-3 05:15:33") 
   strtotime("now") 
   strtotime("10 September 2000")
   strtotime("-1 day")
   strtotime("+1 week")
   strtotime("+2 week 3 days 4 hours 2 seconds")
   strtotime("next Thursday")
   strtotime("last Monday")




二、函数getdate(timestamp) -- 根据时间戳返回包含日期和时间信息的数组。timestamp为空,则为当前时间。

   举例:
   $d=getdate(); 
   
   echo $d["hours"]."-".$d["minutes"]."-".$d["seconds"]; //时间
   echo $d["year"]."-".$d["mon"]."-".$d["mday"]; //年月日



三、函数date(format,timestamp) --根据时间戳返回指定格式的信息。timestamp默认为当前时间。

   也可以使用idate(format,timestamp)。两者有什么区别?好像date函数的format可选命令更多一些。普通情况可认为两者相同。这是php的一个混乱之处。

  
   举例:
   idate("t") - 返回本月的总天数
   
   idate("z") - 今天是一年中的第几天

   date("Y-m-d H:i:s") 显示类似“2020-01-3 20:19:21”

   date('t',strtotime("2020-4-1")); //返回2020年4月总的天数



   
四、DateTime对象

   
$datetime = new DateTime();

$datetime->setDate(年,月,日);

$datetime->setTime(时,分,秒);

$datetime->setTimestamp(时间戳);

$datetime->format(输出格式); //比如'Y-m-d H:i:s'

$datetime->modify("运算字符串");

获取时间戳:
$datetime->getTimestamp();


用date_create函数创建:

$datetime=date_create("2014-05-12 21:20:00",timezone可选);
echo date_format($datetime,"Y/m/d");


设置时间:
date_time_set($datetime,hour,minute,second);
  


五、运算

1、利用strtotime函数进行日期时间的运算

   日期加法举例:

   $d = "2018-03-12 12:15:20";
   echo date("Y-m-d", strtotime("$d   +1   year"));

2、date_diff() -- 日期相差

   $date1=date_create("2020-03-15");
   $date2=date_create("2017-12-12");
   $diff=date_diff($date1,$date2);

3、date_add() -- 日期加法

   举例:加上100天
   $date=date_create("2020-03-15");
   date_add($date,date_interval_create_from_date_string("100 days"));
   echo date_format($date,"Y-m-d");

4、date_sub() -- 日期减法

    $date=date_create("2019-09-29");
    date_sub($date,date_interval_create_from_date_string("100 days"));
    echo date_format($date,"Y-m-d");



(未完待续)


热门