PHP: Convert Local Time to UTC

霸气de小男生 提交于 2019-12-02 04:06:52

问题


Assume I get a string like 08/22/2015 10:56 PM and that this date/time string always refers to only one particular time zone. I need to be able to convert that to this format: 'Ymd\THis\Z', which is the iCal format.

  1. How do I convert that string to Zulu time and into 'Ymd\THis\Z'
  2. How do I then add, say, 30 minutes to that date/time?

Been trying to hack this with strtotime and DateTime, but I'm worried that I'm going about this the wrong way. Maybe there's a simpler and more straightforward solution?


回答1:


You can use DateTime, example bellow:

<?php

$datetime = '08/22/2015 10:56 PM';
$tz_from = 'America/New_York';
$tz_to = 'UTC';
$format = 'Ymd\THis\Z';

$dt = new DateTime($datetime, new DateTimeZone($tz_from));
$dt->setTimeZone(new DateTimeZone($tz_to));
echo $dt->format($format) . "\n";

$minutes = 30;
$dt->add(new DateInterval('PT' . $minutes . 'M'));
echo $dt->format($format) . "\n";



回答2:


according to subject line; To convert local time to UTC you need the timezone name of given local time, or if you have timezone offset in GMT; you can try the following:

//assume time zone is +3 hours
$offset = 3 * 60 * 60;
$date = date('H:i:s', strtotime("10:56 PM")- $offset);
echo $date;

This will output : 19:56:00 which is UTC Time



来源:https://stackoverflow.com/questions/32139407/php-convert-local-time-to-utc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!