I'm using this code:
$due_date = new DateTime[$_POST['due_date']];
$today = new DateTime[];
$months = $due_date->diff[$today];
$months->format["%m"];
$fine = 0.02 * $price * $months; // i got error in this line
$bill = $price + $fine;
I want to calculate, if someone is late to pay then they will be fined per month. And the error message is:
Object of class DateInterval could not be converted to int
asked Jun 25, 2016 at 13:44
2
The error message appears because $months
is not an int, but a Datetime object like this one:
DateInterval Object
[
[y] => 0
[m] => 4
[d] => 12
[h] => 6
[i] => 56
[s] => 9
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 133
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
]
You can get the integer value of months like this
$due_date = new DateTime['13-02-2016'];
$today = new DateTime[];
$months = $due_date->diff[$today];
echo $months->m;
Check the above result in PHP Sandbox
So basically your code will look like
$due_date = new DateTime[$_POST['due_date']];
$today = new DateTime[];
$months = $due_date->diff[$today];
$fine = 0.02 * $price * $months->m; // i got no error in this line
$bill = $price + $fine;
answered Jun 25, 2016 at 13:51
1
You calculate the difference in months, but you never actually use that value. The format
method outputs something, but doesn't change the actual DateInterval.
Try it like this:
$due_date = new DateTime[$_POST['due_date']];
$today = new DateTime[];
$diff = $due_date->diff[$today];
$months = $diff->format["%m"];
$fine = 0.02 * $price * $months;
$bill = $price + $fine;
answered Jun 25, 2016 at 13:48
PevaraPevara
14.1k1 gold badge32 silver badges47 bronze badges
3
Peter Darmis's answer is wrong. I can't downvote nor comment it so I will add this new answer.
DateInterval represents a period of time by deconstructing the interval in different parts, years, months, days etc... So "m" in the proposed solution will never be bigger than 12.
So you should probably do something like this:
$due_date = new DateTime['13-02-2016'];
$today = new DateTime[];
$diff = $due_date->diff[$today];
$months = [$diff->y * 12] + $diff->m;
echo $months;
Check it in the sandbox: //sandbox.onlinephpfunctions.com/code/907b39ffee4586c4c9481ff3e0ea1aeb2d27c7b8
answered Sep 13, 2019 at 14:35
iblancoiblanco
411 silver badge6 bronze badges
[PHP 5 >= 5.3.0, PHP 7, PHP 8]
DateInterval::__construct — Creates a new DateInterval object
Description
public DateInterval::__construct[string $duration
]
Parameters
duration
An interval specification.
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
.
duration
Period Designators Y
| years |
M
| months |
D
| days |
W
| weeks. Converted into days. Prior to PHP 8.0.0, can not be combined with D .
|
H
| hours |
M
| minutes |
S
| seconds |
Here are some simple examples. Two days is P2D
. Two seconds is PT2S
. Six years and five minutes is P6YT5M
.
Note:
The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as
P1Y4D
, notP4D1Y
.
The specification can
also be represented as a date time. A sample of one year and four days would be P0001-00-04T00:00:00
. But the values in this format can not exceed a given period's roll-over-point [e.g. 25
hours is invalid].
These formats are based on the » ISO 8601 duration specification.
Errors/Exceptions
Throws an
Exception when the duration
cannot be parsed as an interval.
Changelog
8.2.0 | Only the y to f , invert , and days will be visible, including a new from_string boolean property.
|
8.0.0 | W can be combined with D .
|
Examples
Example #1 Constructing and using DateInterval objects
Output of the above example in PHP 8.2:
object[DateInterval]#1 [10] { ["y"]=> int[0] ["m"]=> int[0] ["d"]=> int[9] ["h"]=> int[0] ["i"]=> int[0] ["s"]=> int[0] ["f"]=> float[0] ["invert"]=> int[0] ["days"]=> bool[false] ["from_string"]=> bool[false] }
Output of the above example in PHP 8:
object[DateInterval]#1 [16] { ["y"]=> int[0] ["m"]=> int[0] ["d"]=> int[9] ["h"]=> int[0] ["i"]=> int[0] ["s"]=> int[0] ["f"]=> float[0] ["weekday"]=> int[0] ["weekday_behavior"]=> int[0] ["first_last_day_of"]=> int[0] ["invert"]=> int[0] ["days"]=> bool[false] ["special_type"]=> int[0] ["special_amount"]=> int[0] ["have_weekday_relative"]=> int[0] ["have_special_relative"]=> int[0] }
Output of the above example in PHP 7:
object[DateInterval]#1 [16] { ["y"]=> int[0] ["m"]=> int[0] ["d"]=> int[2] ["h"]=> int[0] ["i"]=> int[0] ["s"]=> int[0] ["f"]=> float[0] ["weekday"]=> int[0] ["weekday_behavior"]=> int[0] ["first_last_day_of"]=> int[0] ["invert"]=> int[0] ["days"]=> bool[false] ["special_type"]=> int[0] ["special_amount"]=> int[0] ["have_weekday_relative"]=> int[0] ["have_special_relative"]=> int[0] }
See Also
- DateInterval::format[] - Formats the interval
- DateTime::add[] - Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
- DateTime::sub[] - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
- DateTime::diff[] - Returns the difference between two DateTime objects
owen at beliefs.com ¶
9 years ago
M is used to indicate both months and minutes.
As noted on the referenced wikipedia page for ISO 6801 //en.wikipedia.org/wiki/Iso8601#Durations
To resolve ambiguity, "P1M" is a one-month duration and "PT1M" is a one-minute duration [note the time designator, T, that precedes the time value].
Using: PHP 5.3.2-1ubuntu4.19
// For 3 Months
$dateTime = new DateTime;echo $dateTime->format[ DateTime::ISO8601 ], PHP_EOL;
$dateTime->add[new DateInterval["P3M"]];
echo $dateTime->format[ DateTime::ISO8601 ], PHP_EOL;
Results in:
2013-07-11T11:12:26-0400
2013-10-11T11:12:26-0400
// For 3 Minutes
$dateTime = new DateTime;echo $dateTime->format[ DateTime::ISO8601 ], PHP_EOL;
$dateTime->add[new DateInterval["PT3M"]];
echo $dateTime->format[ DateTime::ISO8601 ], PHP_EOL;
Results in:
2013-07-11T11:12:42-0400
2013-07-11T11:15:42-0400
Insert a T after the P in the interval to add 3 minutes instead of 3 months.
buvinghausen at gmail dot com ¶
10 years ago
I think it is easiest if you would just use the sub method on the DateTime class.
Instead you have to create first the interval and then set its 'invert' property to 1, this is:
Then you should keep in mind that this interval acts as a negative number, hence to subtract the interval from a given date you must 'add' it:
kevinpeno at gmail dot com ¶
11 years ago
Note that, while a DateInterval object has an $invert property, you cannot supply a negative directly to the constructor similar to specifying a negative in XSD ["-P1Y"]. You will get an exception through if you do this.
Instead you need to construct using a positive interval ["P1Y"] and the specify the $invert property === 1.
daniellehr at gmx dot de ¶
10 years ago
Alternatively you can use DateInterval::createFromDateString[] for negative intervals:
will yield 0:0:3600 instead of the expected 1:0:0
jawzx01 at gmail dot com ¶
10 years ago
As previously mentioned, to do a negative DateInterval object, you'd code:
and then $date1 is now 89 days in the past.
admin at torntech dot com ¶
7 years ago
Warning - despite the $interval_spec accepting the ISO 8601 specification format, it does not accept decimal fraction values with period or comma as stated in the specification.
//bugs.php.net/bug.php?id=53831
Will result in
Fatal error: Uncaught exception 'Exception' with message 'DateInterval::__construct[]: Unknown or bad format [P0.5Y]'
userexamplecom at mailinator dot com ¶
6 years ago
Take care, if you have a DateTime Object on the 31h of January and add Da DateInterval of one Month, then you are in March instead of February.
For Example:
---
// given the actual date is 2017-01-31
$today = new DateTime['now', $timeZoneObject];
$today->add[new DateInterval['P1M']];
echo $today->format['m'];
// output: 03
---
lsloan-php dot net at umich dot edu ¶
6 years ago
Although PHP refers to periods of time as "intervals", ISO 8601 refers to them as "durations". In ISO 8601, "intervals" are something else.
While ISO 8601 allows fractions for all parts of a duration [e.g., "P0.5Y"], DateInterval does not. Use caution when calculating durations. If the duration has a fractional part, it may be lost when storing it in a DateInterval object.
Anonymous ¶
1 year ago
Note that to add time you must enter P even though the period is empty.
To add 1 hour :
grzeniufication ¶
2 years ago
If you'd like to persist an interval object in a DB it could be handy to implement the __toString[] method. A formatted interval value can be easier to read by a human than the output of serialize. Here's an example: