0

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))
4
  • It's kind of a bad idea to use offsets! Can you not solve your problem with the DateTimeZone object instead? Commented Dec 31, 2018 at 20:13
  • @Evert Hey, I can use all the feedback I can get. The bottom line is, I have these course times in different timezones and I am going to need to translate them based on the current browser's timezone. UTC seems to be the best option for this? Am I wrong? Thx for the input. Commented Dec 31, 2018 at 20:22
  • Converting to UTC might cause some future dates to incorrect. The two major things that impact this is twice-yearly DST changes and changes to the timezone database. If you are doing things with the frontend (in javascript) take a look at the Moment.js package. It supports the same timezone strings. Commented Dec 31, 2018 at 20:28
  • Please read "time zone != offset" in the timezone tag wiki. Thanks. Commented Dec 31, 2018 at 23:19

1 Answer 1

2

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');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.