如何在Carbon实例中添加CarbonInterval实例 [英] How to add CarbonInterval instance in Carbon instance

查看:188
本文介绍了如何在Carbon实例中添加CarbonInterval实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个碳实例

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

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

和CarbonInterval实例

and a CarbonInterval instance

   $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,
   }

如何在碳实例中添加间隔,这样我就可以得到

How to add the interval in the carbon instance so that I would get

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

我知道这样的解决方案,涉及将其转换为这样的timestamp或Datetime类

I am aware of solution that involve converting it to timestamp or Datetime class like this

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

这是我目前正在使用的,但是我正在寻找一种通过官方网站,但找不到任何相关内容,因此需要一些帮助.

which is what currently I am using but I am looking for a more "carbony" way I searched through the official site but couldn't find anything on this so need some help.

更新: 只是为了给你上下文 在前端,我有两个控件,第一个是间隔(天,月,年),第二个是文本框,因此根据组合,我会动态生成字符串,例如"2 days","3 months"然后将其馈给间隔类

Update: Just to give you the context On frontend I have two controls 1st is for interval (days,months,year) 2nd is a text box so depending on the combination I generate strings dynamically like "2 days" , "3 months" so on that then gets feed to interval classes

推荐答案

我不知道有一个内置函数来添加间隔,但是应该起作用的是将间隔的总秒数添加到日期:

I'm not aware of a built-in function to add an interval, but what should work is adding the total seconds of an interval to the date:

$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是基于DateTime的,而CarbonInterval是基于DateInterval的.有关方法参考,请参见此处.

This works because Carbon is based on DateTime and CarbonInterval is based on DateInterval. See here for method reference.

这篇关于如何在Carbon实例中添加CarbonInterval实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆