adam78
adam78

Reputation: 10078

How to create a Carbon date in Laravel

How do you I create a Carbon date if I have the date part in the following format 'd M Y' and I have hours and minutes in separate variables as integers.

eg.

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

Currently I'm having to do this but it also ends up adding the current seconds.

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

result 2016-02-06 12:00:44

Is there a more cleaner way to create a carbon date without having to chain the hours and minutes and to set the seconds to 00?

Maybe something like this but it doesn't work:

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

* UPDATE *

Manage to figure out:

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

Upvotes: 0

Views: 1676

Answers (2)

Grzegorz Gajda
Grzegorz Gajda

Reputation: 2474

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();

Solution:

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

Upvotes: 2

Ammar Ajmal
Ammar Ajmal

Reputation: 354

If you are willing to use createFromFormat than you have to inout the second argument as a string like this :

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

Upvotes: 1

Related Questions