Home > Back-end >  setTime Carbon also affexts other variable
setTime Carbon also affexts other variable

Time:11-13

I have Carbon Object Date which I change the time for a start_date and end_date, what happens is it both becomes the same thing even though I saved it on a seperate variable.

Input

    $this->temp_mon_start = $date->setTime(8,0);
    $this->temp_mon_end = $date->setTime(3,0);  
    dd($this->temp_mon_start, $this->temp_mon_end);

Output

   date: 2021-11-15 03:00:00.0 Asia/Singapore ( 08:00)
   date: 2021-11-15 03:00:00.0 Asia/Singapore ( 08:00)

It appears it saves the last setTime on the $date variable, which I don't know what is causing the issue. I'm using Laravel and Carbon. Is there any possible alternative on this? Appreciate the help.

CodePudding user response:

Well Carbon works that way. It does not create a new instance but rather changes existing one.

So insted of using:

$this->temp_mon_start = $date->setTime(8,0);

you can use:

$this->temp_mon_start = $date->copy()->setTime(8,0);

copy() method creates new instance of Carbon object.

  • Related