jeetgeg's avatar

How to change ISO_8601 in UTC to mysql timestamp

$date = '2018-04-16T07:03:06Z';

// in migration I have used

$table->timestampTz('my_date')->nullable();

//when creating record

$user = new User();
$user->my_date = $date; // how can change to mysql timestamp
$user->save()

How can i change it to Mysql timestamp when creating record in db. It should also preserve the timezone info with it.

Please help.

0 likes
6 replies
Cronix's avatar
Cronix
Best Answer
Level 67
use Carbon\Carbon;

$date = Carbon::parse('2018-04-16T07:03:06Z');

?

1 like
Talinon's avatar

I'm not exactly sure what you're trying to do.. Is it important that the actual data within the database is in ISO_8601 format, or do you just need it converted for application logic?

If you are just looking for a way of working with the timestamp within your application, you might want to look into Carbon (it's included with Laravel)

https://carbon.nesbot.com/docs/

To take it a step further, if you wish to always have a Carbon instance of your my_date field, you can create a Model accessor within your User model:

public function getMyDateAttribute($value)
{
    return \Carbon\Carbon::parse($value);
}

This way whenever you try to access $user->my_date you will get a Carbon instance of your date/timestamp, and you can do whatever you wish with it.

jeetgeg's avatar

Thanks @Cronix and @Talinon

Actually I am using an API which is giving me date in ISO_8601 format ( '2018-04-16T07:03:06Z'). I want to store that date value in mysql database without loosing timezone info. I have set the column attribute to timestamp.

Whenever i change my application timezone. It should be shown as per timezone set.

Cronix's avatar

Did you try what I suggested? It should preserve the timezone.

Cronix's avatar

Ah, good. I was going to recommend that approach as well. It's just a lot easier to have everything stored as UTC.

Please or to participate in this conversation.