Date/Time
在线手册:中文  英文

The DateInterval class

(PHP 5 >= 5.3.0)

简介

Represents a date interval.

A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTime's constructor supports.

类摘要

DateInterval {
/* 属性 */
public integer $y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public integer $invert ;
public mixed $days ;
/* 方法 */
public __construct ( string $interval_spec )
public static DateInterval createFromDateString ( string $time )
public string format ( string $format )
}

属性

y

Number of years.

m

Number of months.

d

Number of days.

h

Number of hours.

i

Number of minutes.

s

Number of seconds.

invert

Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format().

days

If the DateInterval object was created by DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE.

Table of Contents


Date/Time
在线手册:中文  英文

用户评论:

artur at qrupa dot com (2012-11-30 11:46:28)

When using DateInterval('P3M') on 30th of November you get March instead of Ferbuary.

p dot scheit at ps-webforge dot com (2011-03-15 06:07:12)

If you want to convert a Timespan given in Seconds into an DateInterval Object you could dot the following:

<?php

$dv 
= new DateInterval('PT'.$timespan.'S');
?>

but wenn you look at the object, only the $dv->s property is set. 

As stated in the documentation to DateInterval::format

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day". 

If you still want to calculate the seconds into hours / days / years, etc do the following:

<?php

$d1 
= new DateTime();
$d2 = new DateTime();
$d2->add(new DateInterval('PT'.$timespan.'S'));
      
$iv $d2->diff($d1);

?>

$iv is an DateInterval set with days, years, hours, seconds, etc ...

jeff dot davies at yahoo dot com (2010-09-14 17:15:31)

This class became available in PHP 5.3. It is not present in 5.2 or earlier releases. I found this out the hard way when you PHP scripts stopped working when I deployed them onto a Yahoo server. Yahoo has 5.2 while my machine hosts 5.3.

sebastien dot michea at manaty dot net (2010-08-29 20:25:53)

It would be nice that when converting a DateInterval to a string, the interval specification used to construct the object is returned (like "P2W").
I need this to serialize a DateInterval object in order to store it in a postgres DB.

易百教程