【问题标题】:How to create a Carbon date in Laravel如何在 Laravel 中创建碳日期
【发布时间】:2016-02-07 03:36:48
【问题描述】:

如果我的日期部分采用以下格式“d M Y”,并且我在单独的变量中以整数形式存在小时和分钟,我将如何创建 Carbon 日期。

例如。

$this->start_dt  = '06 Feb 2016'
$this->start_hr  = '12'
$this->start_min  = '00'

目前我必须这样做,但它最终也会添加当前秒数。

Carbon::createFromFormat('d M Y', $this->start_dt)->hour($this->start_hr)->minute($this->start_min);

结果2016-02-06 12:00:44

有没有更简洁的方法来创建碳日期,而无需链接小时和分钟并将秒设置为 00?

也许是这样,但它不起作用:

Carbon::createFromFormat('d M Y H:i', $this->start_dt, $this->start_hr, $this->start_min);

* 更新 *

设法弄清楚:

 Carbon::createFromFormat('d M Y H:i:s', $this->start_dt . ' ' . $this->start_hr . ':'. $this->start_min . ':00');

【问题讨论】:

  • 不能随便加秒吗?
  • 嘿,喜欢你的编辑

标签: php laravel-5 php-carbon


【解决方案1】:

Documentation: Instantiation

Carbon::createFromDate($year, $month, $day, $tz);
Carbon::createFromTime($hour, $minute, $second, $tz);
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

Documentation: Fluent setters

$dt->year(1975)->month(5)->day(21)->hour(22)->minute(32)->second(5)->toDateTimeString();
$dt->setDate(1975, 5, 21)->setTime(22, 32, 5)->toDateTimeString();
$dt->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString();

解决方案:

Carbon::createFromFormat('d M Y', $this->start_dt)
    ->setTime($this->start_hr, $this->start_min);

【讨论】:

    【解决方案2】:

    如果您愿意使用 createFromFormat ,则必须将第二个参数输入为这样的字符串:

    $dt=Carbon\Carbon::createFromFormat('d M Y H:i', $this->start_dt.' '.$this->start_hr.':'.$this->start_min);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2017-09-06
      • 2017-08-25
      • 2018-03-16
      • 2016-08-09
      • 2016-12-22
      • 2017-11-28
      相关资源
      最近更新 更多