Reputation: 1029
I have a Wordpress marketplace store where the "author" of a product has their timezone stored in usermeta in the string format, i.e. Americas/Chicago
.
I am wanting to output each user's timezone with a UTC offset instead of string so I can more easily manipulate it. I got this example below from another stack overflow question but it isn't working in my situation.
$timezone = 'America/New_York'; //example string although I am getting the timezone from the database based on each users settings
if(!empty($timezone)) {
$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone($timezone);
$date = new DateTime( $newTZ );
$date->setTimezone( $UTC);
echo $date->format('H:i:s');
}
However, this code breaks the page. Can't understand why it would be breaking the page. I put it into a separate function and it still breaks and the error log isn't much help either.
The log says:
DateTime->__construct(Object(DateTimeZone))
Upvotes: 0
Views: 717
Reputation: 219804
The error message is pretty clear:
Fatal error: Uncaught TypeError: DateTime::__construct() expects parameter 1 to be string, object given
The timezone is second parameter for DateTime
. So if you want to work with "now' either pass "now" or null
as the first parameter.
$timezone = 'America/New_York'; //example string although I am getting the timezone from the database based on each users settings
if(!empty($timezone)) {
$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone($timezone);
$date = new DateTime(null, $newTZ );
$date->setTimezone( $UTC);
echo $date->format('H:i:s');
}
Upvotes: 2