Formats the interval

DateInterval::format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::formatFormats the interval

說明

public DateInterval::format(string $format): string

Formats the interval.

參數

format

The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%).
format characterDescriptionExample values
%Literal %%
YYears, numeric, at least 2 digits with leading 001, 03
yYears, numeric1, 3
MMonths, numeric, at least 2 digits with leading 001, 03, 12
mMonths, numeric1, 3, 12
DDays, numeric, at least 2 digits with leading 001, 03, 31
dDays, numeric1, 3, 31
aTotal number of days as a result of a DateTime::diff() or (unknown) otherwise4, 18, 8123
HHours, numeric, at least 2 digits with leading 001, 03, 23
hHours, numeric1, 3, 23
IMinutes, numeric, at least 2 digits with leading 001, 03, 59
iMinutes, numeric1, 3, 59
SSeconds, numeric, at least 2 digits with leading 001, 03, 57
sSeconds, numeric1, 3, 57
FMicroseconds, numeric, at least 6 digits with leading 0007701, 052738, 428291
fMicroseconds, numeric7701, 52738, 428291
RSign "-" when negative, "+" when positive-, +
rSign "-" when negative, empty when positive-,

返回值

Returns the formatted interval.

更新日誌

版本說明
7.1.0The F and f format characters were added.

範例

示例 #1 DateInterval example

<?php

$interval 
= new DateInterval('P2Y4DT6H8M');
echo 
$interval->format('%d days');

?>

以上例程會輸出:

4 days

示例 #2 DateInterval and carry over points

<?php

$interval 
= new DateInterval('P32D');
echo 
$interval->format('%d days');

?>

以上例程會輸出:

32 days

示例 #3 DateInterval and DateTime::diff() with the %a and %d modifiers

<?php

$january 
= new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval $february->diff($january);

// %a will output the total number of days.
echo $interval->format('%a total days')."\n";

// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');

?>

以上例程會輸出:

31 total days
1 month, 0 days

註釋

注意:

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".

參見

Leave a Reply

Your email address will not be published. Required fields are marked *