Is there an easy way to change timezone only on view laravel?

Viewed 4025

So I already save any date on my database with UTC, and I can get it just like $data->created_at or $data->blocked_at. So in my config, I set timezone to UTC, then i want to convert when on view from UTC to UTC+7 or another timezone.

Is there an easy way to convert timezone i want when on view for all dates?

I'm still using Laravel 5.8

Edit:

I'm using the answer but implement that on my base model, like this:

public function getDateConverter($key){
    if(strtotime($this->{$key})){
        $date = Carbon::createFromFormat('Y-m-d H:i:s', $this->{$key});
        $date->setTimezone(env("APP_TIMEZONE_VIEW"));
        return $date->toDateTimeString();
    } else {
        return null;
    }
}

And I will call the column name like this $data->getDateConverter("created_at");

3 Answers

You can use Carbon which is included in the core

$timestamp = '2014-02-06 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Europe/Stockholm');
$date->setTimezone('UTC');

Europe/Stockholm is your default timezone and UTC is what you want to set

If you want to convert it from a model when displaying, try Accessors

public function getCreatedAtAttribute($value)
    {
        $date = Carbon::createFromFormat('Y-m-d H:i:s', $value, 'Europe/Stockholm');
        $date->setTimezone('UTC');
        return $date->toDateTimeString();
    }

well in case if you want to chnage your timezone when inserting the time then

Use 'timezone' => 'Asia/Kolkata'. in your config/app.php

By this you can set your applications default timezone..

you can use add this function to your model

 public function setViewDateFormat( $date ) {
        return Carbon::parse( $date ,'Africa/Cairo')->format( 'j F Y' );
 }

Then call it on any date attribute

public function getFormattedCreatedAtAttribute() {
        return ( $this->created_at ) ? $this->setViewDateFormat( $this->created_at ) : null;
}

This way you can set all dates timezone and format.

Related