Alright so basically, I am a little confused about how the timestamp works in DateTime in PHP. I wish to make two methods that convert from a local time to UTC and vice versa.
I currently have this:
/**
* @param \IPS\DateTime $utcDateTime The UTC datetime.
* @param \DateTimeZone $timezone The timezone to convert the UTC time to.
* @return \IPS\DateTime New datetime object in local datetime.
* @throws \Exception when the UTC date is not in UTC format. (debugging purposes)
*/
public static function utcToLocal($utcDateTime, $timezone)
{
if ($utcDateTime->getTimezone()->getName() !== "UTC") {
throw new \Exception("Date time is not UTC!");
}
$time = new DateTime($utcDateTime, new \DateTimeZone("UTC"));
$time->setTimezone($timezone);
return $time;
}
/**
* @param \IPS\DateTime $localDateTime A datetime configured with the the user's timezone
* @return DateTime New datetime object in UTC format
* @throws \Exception When given datetime is already in UTC (for debugging purposes)
*/
public static function localToUtc($localDateTime)
{
if ($localDateTime->getTimezone()->getName() === "UTC") {
throw new \Exception("Value is already UTC");
}
$time = new DateTime($localDateTime, $localDateTime->getTimezone());
$time->setTimezone(new \DateTimeZone("UTC"));
return $time;
}
When I debug this code, at the last line return $time
in localToUtc(...)
my debugger shows the correct conversions:
However, when I evaluate the expression
$localDateTime->getTimestamp() === $time->getTimestamp()
it will return true.
So I am a little confused, I just want the timestamps to change when I change the timezone. I am thinking maybe I need to work with getOffset()
but I want to make sure I do it in the correct way. I'd also prefer not to use any string format tricks because I feel like that is not the correct way.