Skip to content
Advertisement

Laravel – convert time to user’s timezone in model

I have the following model that returns data from Dynamo AWS, my data has a time in EPOCH, and I convert it to the formatted date as below:

class File extends BaseDynamo
{
    protected $table = 'Dados';
    protected $primaryKey = 'SUI';
    protected $sortKey = ['EPOCH','desc'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'EPOCH' => 'datetime:Y-m-d H:i:s',
    ];
}

However, the time returning does not match the time that the user is seeing the data and that is why I would like to make the conversion using the registration timezone as an extra field in the user:

private function timezone(){
    $user = User::find(Auth::id());
    $extra_field = ExtraField::where('description','=','TimeZone')->first();

    if($extra_field) {
        $timezone = ExtraFieldValue::where('extra_field_id', '=', $extra_field->id)->where('user_id', '=', $user->id)->first()->value;
    } else {
        $timezone = 'America/Sao_Paulo';
    }

    return $timezone;
}

I tried to do something like this: UPDATE

class File extends BaseDynamo
{
    protected $table = 'Dados';
    protected $primaryKey = 'SUI';
    protected $sortKey = ['EPOCH','desc'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'EPOCH' => 'datetime:Y-m-d H:i:s',
    ];

    public function getEpochAttribute($value)
    {
        $user = User::find(Auth::id());
        $extra_field = ExtraField::where('description','=','TimeZone')->first();

        if($extra_field) {
            $timezone = ExtraFieldValue::where('extra_field_id', '=', $extra_field->id)->where('user_id', '=', $user->id)->first()->value;
        } else {
            $timezone = 'America/Sao_Paulo';
        }
        Log::info('timezone');
        Log::info($value);
        Log::info($timezone);
        Log::info($value->setTimezone($timezone)->toDateTimeString("Y-m-d H:i:s"));

        return $value->setTimezone($timezone)->toDateTimeString("Y-m-d H:i:s");
    }
}

It’s not even calling my function, when I do this:

$collection = collect(File::filterBetween('EPOCH', $date)->filter('SUI','=',$asset->mac_id)->scan());
$my_datetime = $collection->whereIn($variable->key, [0,1])->pluck('EPOCH')->last();

But it doesn’t work, can someone help me how to make this conversion?

Advertisement

Answer

I would say read more about Accessors and Mutators

Would be something like

public function getEPOCHAttribute($value)
{
    //Logic to change the date
    return $value;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement