Timezone conversion in php

后端 未结 9 1700
我寻月下人不归
我寻月下人不归 2020-11-22 04:19

Can anyone suggest an easy method to convert date and time to different timezones in php?

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 04:29

    You can use the datetime object or their function aliases for this:

    Example (abridged from PHP Manual)

    date_default_timezone_set('Europe/London');
    
    $datetime = new DateTime('2008-08-03 12:35:23');
    echo $datetime->format('Y-m-d H:i:s') . "\n";
    $la_time = new DateTimeZone('America/Los_Angeles');
    $datetime->setTimezone($la_time);
    echo $datetime->format('Y-m-d H:i:s');
    

    Edit regarding comments

    but i cannt use this method because i need to show date in different time zones as the user login from different locations

    That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.

    in the database i need to get the dates in any single timezone, then only it can be processed properly

    You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.

提交回复
热议问题