I got this sorted in the end. This bit of info from the PHP manual tipped me off:
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).
So my eventual solution was to extend the DateTime
class and override the __construct()
method. My modified class is as follows:
<?php
class timezone extends DateTime {
// Override our __construct method
function __construct($date = "now", $offset = null) {
// If we've not specified an offset
if(is_null($offset)) {
// Assume UTC
$offsetFormat = "+00:00";
$offset = 0;
// Otherwise..
} else {
// Create a new DateTime, and get the difference between that, and another new DateTime that has $offset minutes subtracted from it. Format the results as something like +11:00 or -03:00
$offsetFormat = (new DateTime($date, new DateTimeZone("UTC")))->diff((new DateTime($date, new DateTimeZone("UTC")))->sub(DateInterval::createFromDateString($offset . " minutes")))->format("%R%H:%I");
}
// Next, we get the offset from our $date. If this offset (divided by 60, as we're working in minutes, not in seconds) does NOT equal our offset
if((new DateTime($date))->getOffset() / 60 !== $offset) {
// Overwrite $date, and set it to a new DateTime with $offset minutes subtracted from it
$date = (new DateTime($date, new DateTimeZone("UTC")))->sub(DateInterval::createFromDateString($offset . " minutes"));
// If $date's offset equals $offset
} else {
// An offset has already been applied (we know this because all our pre-offset dates will be in UTC), and we don't need to do it again
$date = (new DateTime($date));
}
// Finally, hand this back to the original DateTime class. This format works out to be something like: 2016-03-10T23:16:37+11:00
parent::__construct($date->format("Y-m-d\TH:i:s") . $offsetFormat, null);
}
}
echo (new timezone())->format("c") . "<br />"; // Will output something like 2016-03-10T12:17:44+00:00
echo (new timezone(null, -660))->format("c") . "<br />"; // Will output something like 2016-03-10T23:17:44+11:00
echo (new timezone("midnight", -660))->format("c") . "<br />"; // Will output 2016-03-10T11:00:00+11:00
echo (new timezone("midnight"))->format("c") . "<br />"; // Will output 2016-03-10T00:00:00+00:00
echo (new timezone("2016-01-01T00:00+00:00", -660))->format("c") . "<br />"; // Will output 2016-01-01T11:00:00+11:00
echo (new timezone("2016-01-01T00:00+11:00", -660))->format("c") . "<br />"; // Will output 2016-01-01T11:00:00+11:00. Note that the offset isn't applied twice!
?>
EDIT: This is now a library that I've open-sourced. Check it out over on GitHub