I want to show an event start time with the correct UTC offset (New York Timezone), so normally it would show this:
June 01, 2001 @ 20:00 UTC-4
But if the event starts during Daylight Saving months the event output would automatically show UTC-5, as 8pm in New York then would be UTC-5:
December 01, 2001 @ 20:00 UTC-5
Is there a way to do this?
With DateTime the closest I can get is without showing the timezone:
'F j, Y @ G:i'
CodePudding user response:
You have a few options, but none of them are exactly what you're looking for. You might have to do a bit of manipulation.
With default formatters, you have O
( 0200), P
or p
( 02:00), and T
(EST, MDT, 05). See https://www.php.net/manual/en/datetime.format.php under timezone identifiers. It won't add the UTC, but you can add it in yourself like 'F j, Y @ G:i \U\T\CP'
, which currently gives me "September 21, 2021 @ 7:51 UTC-04:00"
.
The other option, if you want just the number, is to format it yourself. With the DateTime class, you have getOffset()
, which returns the offset in seconds. With a bit of math, you can get the number
$date = new DateTime();
$offset = $date->getOffset() / 60 / 60; // Divide by 60 seconds to a minute, 60 minutes to an hour
$formatted_date = $date->format('F j, Y @ G:i'). " UTC$offset";
// "September 21, 2021 @ 7:52 UTC-4"
CodePudding user response:
You can have the hours delivered to you with the DateTime Format Option "P" and then format the desired result with sprintf.
function tzUTC(DateTimeInterface $date)
{
$tzHours = (int)$date->format('P');
return sprintf('UTC% 1d',$tzHours);
}
Example:
$date = new DateTime('now',new DateTimezone('America/New_York'));
echo $date->format('F j, Y @ G:i ').tzUTC($date);
Output:
September 21, 2021 @ 9:10 UTC-4