XF 2.3 Display date with given timezone vs user timezone

stromb0li

Well-known member
We have a lot of dates and times posted on our website where we want to display the date in a specific timezone (regardless of the user's or board's preference). Is there a way to override the user's date time and specify a constant timezone to be used when displaying the date, via xf:date tag or date function?

I.e. I would want the date to be shown as mm/dd/yyyy 8:30 AM PST; where PST is the constant or UTC-8, etc.
 
You can use date_from_format. You'll have to adjust the format string.

HTML:
{{ date_from_format('Y-m-d', $timestamp, 'Some/TimeZone') }}
 
I don't seem to see any output using {{ date_from_format('g:i A', $moo.date, 'America/Los_Angeles') }} -- no server error logged using it either though.

If I use {{ date($moo.date, 'g:i A') }} I do see the date, but it gets localized vs stay constant for guests and logged in users (with my timezone set to pacific and board / guest timezone set as UTC, I see the date localized properly as expected).

If I use {{date(date_from_format('U', $moo.date, 'America/Los_Angeles'), 'g:i A')}} I see the date, but always in UTC-0 instead of pacific timezone.

The goal is to take the UTC timestamp and display it in Pacific Time.

Edit: As a workaround, this seems to work, but feels like a really bruteforce way:

Controller:
PHP:
$timestamp = $moo['date'];
$courseTimezone = new \DateTimeZone($moo['timezone']);
$dateTime = new \DateTime("@$timestamp", new \DateTimeZone('UTC')); // Create DateTime from timestamp in UTC
$offset = $courseTimezone->getOffset($dateTime); // Get the offset
$moo['offset'] = $offset;

View:
{{date(date_from_format('U', ($moo.date + $moo.offset), 'UTC'), 'g:i A')}}
 
Last edited:
I don't seem to see any output using {{ date_from_format('g:i A', $moo.date, 'America/Los_Angeles') }} -- no server error logged using it either though.
Right sorry, it produces a \DateTime object for you to use.

If I use {{date(date_from_format('U', $moo.date, 'America/Los_Angeles'), 'g:i A')}} I see the date, but always in UTC-0 instead of pacific timezone.
This is actually a PHP behavior, U, will always create a UTC \DateTime. You can create the \DateTime in PHP and pass it to the template for use with {{ date(...) }}, or use a non-U format to do the conversion:

HTML:
{{ date_time(date_from_format('g:i A', date($xf.time, 'g:i A'), 'America/Los_Angeles'), 'g:i A') }}
 
Last edited:
Back
Top Bottom