Hi,
I am trying to figure out how to change time zone using Eloquent between UTC to user's local timezone.
I have a some datetime fields (i.e. training_at, next_scheduled_at, read_on, engaged_on.....) the value for these fields is something a user enters from the frontend app. Each user types the value using their local time zone. I will need to convert the datetime value provided by the user to UTC time zone prior to saving it to the database. Every timezone value must be UTC when it is stored in the database
Additionally, when retrieving these values from the database "depending on the current user's time zone" the date time must be converted from UTC to user's timezone. (example, if the user in California then -8 Hours from the value or -7 if there is day time saving. If the user is in New York, tjem -5/-4 hours prior displaying it)
Moreover, I would like to convert the created_at, updated_at from UTC to the user's time zone on read.
What is the best way to do this?
In the past I have use these 2 helper methods but like to learn the laravel way to handle this.
//this function convert string to UTC time zone
function convertTimeToUTCzone($str, $userTimezone, $format = 'Y-m-d H:i:s'){
$new_str = new DateTime($str, new DateTimeZone( $userTimezone ) );
$new_str->setTimeZone(new DateTimeZone('UTC'));
return $new_str->format( $format);
}
//this function converts string from UTC time zone to current user timezone
function convertTimeToUSERzone($str, $userTimezone, $format = 'Y-m-d H:i:s'){
if(empty($str)){
return '';
}
$new_str = new DateTime($str, new DateTimeZone('UTC') );
$new_str->setTimeZone(new DateTimeZone( $userTimezone ));
return $new_str->format( $format);
}