如何在Carbon实例中添加CarbonInterval实例

问题描述 投票:3回答:2

我有一个碳实例

   $a = Carbon\Carbon::now();

   Carbon\Carbon {
     "date": "2018-06-11 10:00:00",
     "timezone_type": 3,
     "timezone": "Europe/Vienna",
   }

和一个CarbonInterval实例

   $b = CarbonInterval::make('1month');


     Carbon\CarbonInterval {
     "y": 0,
     "m": 1,
     "d": 0,
     "h": 0,
     "i": 0,
     "s": 0,
     "f": 0.0,
     "weekday": 0,
     "weekday_behavior": 0,
     "first_last_day_of": 0,
     "invert": 0,
     "days": false,
     "special_type": 0,
     "special_amount": 0,
     "have_weekday_relative": 0,
     "have_special_relative": 0,
   }

如何在碳实例中添加区间以便我得到

   Carbon\Carbon {
     "date": "2018-07-11 10:00:00",
     "timezone_type": 3,
     "timezone": "Europe/Vienna",
   }

我知道解决方案涉及将其转换为时间戳或Datetime类

strtotime( date('Y-m-d H:i:s', strtotime("+1 month", $a->timestamp ) ) );  

这是我目前正在使用的,但我正在寻找一种更加“愚蠢”的方式,我搜索了official site但无法找到任何关于此,所以需要一些帮助。

更新:只是为了给你上下文在前端我有两个控件第一个是间隔(天,月,年)第二个是一个文本框所以根据组合我动态生成字符串像“2 days”,“3 months”所以然后在那里得到间隔类的饲料

php laravel php-carbon
2个回答
4
投票

我不知道添加间隔的内置函数,但应该做的是将间隔的总秒数添加到日期:

$date = Carbon::now(); // 2018-06-11 17:54:34
$interval = CarbonInterval::make('1hour');

$laterThisDay = $date->addSeconds($interval->totalSeconds); // 2018-06-11 18:54:34

编辑:找到一个更简单的方法!

$date = Carbon::now(); // 2018-06-11 17:54:34
$interval = CarbonInterval::make('1hour');

$laterThisDay = $date->add($interval); // 2018-06-11 18:54:34

这是因为Carbon基于DateTimeCarbonInterval基于DateInterval。有关方法参考,请参阅here


1
投票

请参阅文档https://carbon.nesbot.com/docs/#api-addsub

$carbon = Carbon\Carbon::now();
$monthLater = clone $carbon;
$monthLater->addMonth(1);
dd($carbon, $monthLater);

结果是

Carbon {#416 ▼
  +"date": "2018-06-11 16:00:48.127648"
  +"timezone_type": 3
  +"timezone": "UTC"
}

Carbon {#418 ▼
  +"date": "2018-07-11 16:00:48.127648"
  +"timezone_type": 3
  +"timezone": "UTC"
}

对于此间隔[月,几个世纪,几年,几个季度,几天,一个星期,几周,几小时,几分钟,几秒],您可以使用类型

$count = 1; // for example
$intrvalType = 'months'; // for example
$addInterval = 'add' . ucfirst($intrvalType);
$subInterval = 'sub' . ucfirst($intrvalType);
$carbon = Carbon\Carbon::now();
dd($carbon->{$addInterval}($count));
dd($carbon->{$subInterval}($count));
© www.soinside.com 2019 - 2024. All rights reserved.