Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

datetime - timezone with DST handling by PHP

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:

  • Whether the PHP APIs used above take care of DST for all regions?
  • The DST time itself changes in different years, how does PHP gets information about this? do we need to upgrade PHP? If so do we need to upgrade all or particular PHP library?

References: - does-phps-date-default-timezone-set-adjust-to-daylight-saving - get-timezone-offset-for-a-given-location

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...