I am working on a calendar application. In this users from different time-zones create/view events. I am thinking to follow below method to save event time in UTC and display them in user's local time. Note: user has their preferred timezone setting.
To save event start time as UTC timestamp:
$timezone = new DateTimeZone( $user_timezone_name );
$utcOffset = $timezone->getOffset( new DateTime( $event_start_time_string_local ) );
$event_start_timestamp_local = maketime( $event_start_time_string_local );
//Now add/subtract $utcOffset to/from $event_start_timestamp_local to get event's start //time timestamp in UTC and save this result in DB.
To get event start time in user's timezone:
date_default_timezone_set( $user_timezone_name );
$eventTimeLocalTime = date("Y-m-d H:i:s", $event_start_timestamp_in_UTC );
Where:
user_timezone_name is user's timezone setting.
event_start_time_string_local is event's start time string in local/civil time.
event_start_timestamp_in_UTC is event's start time timestamp in UTC.
My questions:
References: - does-phps-date-default-timezone-set-adjust-to-daylight-saving - get-timezone-offset-for-a-given-location
You're way too overcomplicating this. To convert between two timezones using DateTime
, do this:
date_default_timezone_set('Asia/Kolkata'); // YOUR timezone, of the server
$date = new DateTime($input, new DateTimeZone('Asia/Tokyo')); // USER's timezone
$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:s');
This converts from a user's local timezone to UTC. To go the other way around, to display the time in the user's local time, swap the two timezones.
Yes, PHP takes care of DST. The necessary conversion rules are part of the PHP installation. You can keep them up to date by updating PHP, or by updating the timezonedb.