uncovery
uncovery

Reputation: 868

How can I create a DateTime object from a string that is already in a specific timezone?

I am working within an environment (wordpress) in which all default timezone settings are set to UTC.

Within that, I want to create a timer function that deals with the time always in the local server time (+8).

The goal is to have a function that returns a DateTime object to any given date (input with a 'Y-m-d H:i:s' format, always in the local +8 timezone

function datetime_obj($date = NULL) {
    $date_new = new DateTime($date);
    $date_new->setTimezone(new DateTimeZone('Asia/Hong_Kong'));
    return $date_new;
}

This works great when I try to get today's date/time information ($date = NULL). However if I have an existing time (in HKG time) as a string (say from a datetime field in a MySQL database), I cannot generate a new datetime object from it since it is treated as UTC. The resulting DateTime object from the function above has always added 8 hours to it.

How can I change the above function so that a $date that is inserted is accepted as already being in the correct +8 timezone and not changed +8 as an output?

Upvotes: 3

Views: 94

Answers (1)

iteratus
iteratus

Reputation: 155

I haven't tried it, but the doc says:

public DateTime::__construct() ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

time: A date/time string. Valid formats are explained in Date and Time Formats. Enter NULL here to obtain the current time when using the $timezone parameter.

timezone: A DateTimeZone object representing the timezone of $time. If $timezone is omitted, the current timezone will be used.

Note: The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

https://www.php.net/manual/en/datetime.construct.php

so... this:

$date_new = new DateTime($date."+08:00");

or this:

$date = new DateTime($date, new DateTimeZone('Asia/Hong_Kong'));

should do the job

Upvotes: 2

Related Questions