Andrei
Andrei

Reputation: 3598

Calculate UTC time when I know the timezone and the time in that timezone

I have a legacy system that does some magic with time.

I can set the timezone(ex: Europe/Bucharest somewhere in the legacy system. An admin can enter a time somewhere in the backend BUT it will always be UTC time.

Once the time is saved in the database it will take into account the above set timezone. So even though the admin entered say 10 PM the time in the database will be 7 PM(yes, it's a little stupid, I agree).

If I was to take the time directly from the database, which I am doing, the time won't be what the admin actually entered, it will be adjusted to the timezone.

Long story short: How can I calculate the correct UTC time if I know the timezone and the time in that timezone? Ex: go from 7 PM to 10 PM, when I know that the timezone is Europe/Bucharest. I want to do this in a non-hackish way.

Upvotes: 0

Views: 118

Answers (2)

Jarek.D
Jarek.D

Reputation: 1294

My understanding is your system stores the dates as UTC (which is a good idea if the system potentially needs to be accessed by users from different timezones). I also understand that when Admin enters date it's get converted to UTC before saving in DB (which is also quite sensible approach)? And now you need to be able to read from database and present the date in the local time:

$database_time = '2017-09-02T21:00:00'; 
$date_obj = DateTime::createFromFormat('Y-m-d\TH:i:s', $database_time, new DateTimeZone('UTC'));
$your_tz = new DateTimeZone('Europe/Warsaw');
$date_obj->setTimeZone($your_tz);
var_dump($date_obj);

If you need to do the opposite (saving the local time as UTC in DB or just show UTC time) then:

$local_time = '2017-09-02T23:00:00'; 
$date_obj = DateTime::createFromFormat('Y-m-d\TH:i:s', $database_time, new DateTimeZone('Europe/Warsaw'));
$db_tz = new DateTimeZone('UTC');
var_dump($date_obj);

If however the database stores data in known timezone, and you simply need to convert that time to UTC it's a matter of:

$database_time = '2017-09-02T21:00:00'; 
$date_obj = DateTime::createFromFormat('Y-m-d\TH:i:s', $database_time, new DateTimeZone('Europe/Warsaw'));
$date_obj->setTimeZone(new DateTimeZone('UTC'));
echo $date_obj->format('Y-m-d\TH:i:s');

Upvotes: 2

Andrei
Andrei

Reputation: 3598

To answer my own question I guess...

(if anybody wants to add or correct me, really, please do).

$database_time = '2017-09-02T21:00:00';

$diff = date('Z', strtotime($database_time)) / 3600; // to get the diff in hours, by default it's in seconds

$UTC_time = (new DateTime($database_time))->modify("+ $diff hour");

$UTC_time->format('m-d-Y H:i:s');

Upvotes: 0

Related Questions