编程语言
首页 > 编程语言> > PHP将DateInterval转换为int

PHP将DateInterval转换为int

作者:互联网

我正在使用此代码:

$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;

我想计算一下,如果有人迟到,那么他们将每月被罚款.错误消息是:

Object of class DateInterval could not be converted to int

解决方法:

出现错误消息是因为$months不是一个int,而是一个类似这样的Datetime对象:

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
)

你可以这样获得月份的整数值

$due_date = new DateTime('13-02-2016');

$today = new DateTime();
$months = $due_date->diff($today);

echo $months->m;

PHP Sandbox中检查以上结果

所以基本上你的代码看起来像

$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;

标签:date-math,dateinterval,datetime,php,date
来源: https://codeday.me/bug/20191118/2028532.html