lumencastuser's avatar

Losing timezone from Carbon object when saving to MySQL datetime column

Hi all,

I'm receiving the following string as input parameter to my application: 2017-07-11T20:15:00+02:00Z

I would like to save this date to UTC in MySQL but I keep losing the timezone (+02:00)...

$input = '2017-07-11T20:15:00+02:00Z'
$date= new Carbon($input);

When checking the object the timezone is present:
dd($date);

object(Carbon\Carbon)#96 (3) {
  ["date"]=>
  string(26) "2017-07-11 20:15:00.000000"
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "+02:00"
}

$hello->data_column = $date;
$hello->save();

After saving the object to MySQL, the wrong date is stored:

2017-07-11 20:15:00

Anyone has an idea what I'm doing wrong?

Thanks in advance!

0 likes
6 replies
jlrdw's avatar

At the bottom of every answer box you see this

Use Markdown with GitHub-flavored code blocks

Please click the link, and properly post the code. code goes between 3 backticks

"```"

code

"```"

without apostrophes.

and use correct indentation.

Cronix's avatar

Is the servers timezone +2:00 (/config/app.php)? Default tz for the server is UTC, so you'd need to convert it to UTC just before saving.

lumencastuser's avatar

Hi All,

@jlrdw: Thanks for the heads-up, fixed now.

@Cronix:

If I'm not mistaken, in Lumen the timezone is set in:

vendor/laravel/lumen-framework/config/app.php

'timezone' => '+00:00'

How can I convert the Carbon object (with timezone) to UTC and save it to MySQL?

Thanks!

lumencastuser's avatar
lumencastuser
OP
Best Answer
Level 1

Problem looks easy fixed by adding:

$date->setTimezone('UTC');
1 like
Cronix's avatar

which is exactly what I said lol

spekkionu's avatar

If you want timezone to be saved with the date you will need to use a timestamp column rather than datetime.

Please or to participate in this conversation.