【问题标题】:PHP Converting DateInterval to intPHP将DateInterval转换为int
【发布时间】:2016-06-25 13:44:10
【问题描述】:

我正在使用此代码:

$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->format("%m");的返回值做任何事情。
  • $months 是一个 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 )

标签: php date datetime dateinterval date-math


【解决方案1】:

出现错误信息是因为$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;

【讨论】:

  • @Pevara 谢谢,format 这个答案不需要它
【解决方案2】:

您以月为单位计算差异,但您从未实际使用该值。 format 方法会输出一些内容,但不会更改实际的 DateInterval。

试试这样:

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

【讨论】:

  • $months = $due_date->diff($today)->format("%m"));
  • @splash58 当然,或者$months = (new DateTime($_POST['due_date']))->diff(new DateTime())->format("%m");...我只是想指出difference ;)
  • 如果它在您的 php 版本 (
【解决方案3】:

Peter Darmis 的回答是错误的。我不能投票也不能评论它,所以我会添加这个新答案。

DateInterval 通过解构不同部分、年、月、日等的间隔来表示一个时间段......所以建议解决方案中的“m”永远不会大于 12。

所以你可能应该这样做:

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

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

$months = ($diff->y * 12) + $diff->m;

echo $months;

在沙箱中检查: http://sandbox.onlinephpfunctions.com/code/907b39ffee4586c4c9481ff3e0ea1aeb2d27c7b8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2014-04-17
    • 2020-10-30
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2016-09-21
    相关资源
    最近更新 更多