php convert datetime to UTC

后端 未结 16 1025
無奈伤痛
無奈伤痛 2020-11-27 12:30

I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.

16条回答
  •  醉梦人生
    2020-11-27 12:52

    If you don't mind using PHP's DateTime class, which has been available since PHP 5.2.0, then there are several scenarios that might fit your situation:

    1. If you have a $givenDt DateTime object that you want to convert to UTC then this will convert it to UTC:

      $givenDt->setTimezone(new DateTimeZone('UTC'));
      
    2. If you need the original $givenDt later, you might alternatively want to clone the given DateTime object before conversion of the cloned object:

      $utcDt = clone $givenDt;
      $utcDt->setTimezone(new DateTimeZone('UTC'));
      
    3. If you only have a datetime string, e.g. $givenStr = '2018-12-17 10:47:12', then you first create a datetime object, and then convert it. Note this assumes that $givenStr is in PHP's configured timezone.

      $utcDt = (new DateTime($givenStr))->setTimezone(new DateTimeZone('UTC'));
      
    4. If the given datetime string is in some timezone different from the one in your PHP configuration, then create the datetime object by supplying the correct timezone (see the list of timezones PHP supports). In this example we assume the local timezone in Amsterdam:

      $givenDt = new DateTime($givenStr, new DateTimeZone('Europe/Amsterdam'));
      $givenDt->setTimezone(new DateTimeZone('UTC'));
      

提交回复
热议问题