Add utility function to handle dates timezone conversions
Most of the time we store dates and time in UTC. But then we have cases were the site timezone is disregarded (Memberships for example) and thus there might be some discrepancy in what the users see (thinking that's date-time in their timezone) and what the extension actually handles, a different time offset.
Storing time in UTC is fine, but we might want to have a shared function to help out with timezone offsets. Eventually we might also want to convert one date in one timezone to another.
So we have four factors: date-time, date-time format, timezone to convert from (UTC or other?), timezone to convert to.
For memberships I was going for something along these lines but it can be adapted (this function assumes the date format Memberships uses and also it only converts from UTC)
function wc_memberships_adjust_utc_date_by_timezone( $date, $format = 'Y-m-d H:i:s', $timezone = '' ) {
if ( is_int( $date ) ) {
$date = date( $format, $date );
}
if ( is_int( $date ) ) {
$src_date = date( $format, $date );
} else {
$src_date = $date;
}
$timezone = new DateTimeZone( $timezone );
$adj_date = new DateTime( $src_date, new DateTimeZone( 'UTC' ) );
$offset = $timezone->getOffset( $adj_date );
// getTimestamp method not used here for PHP 5.2 compatibility
$timestamp = intval( $adj_date->format( 'U' ) );
return is_int( $date ) ? $timestamp + $offset : date( $format, $timestamp + $offset );
}
thinking about it, since @maxrice mentioned the idea of copying some Carbon ideas into the framework, the feature mentioned in this issue could be part of that - it may be worth if handling dates is a very recurring thing among many plugins
Cool. I think the 1st step here is a survey of what timezone-related code we have in our extensions so we can figure out what would be most helpful to abstract into a framework helper.
I'll add my vote for this, since I'm basically doing all the same date manipulations, formatting, parsing in PDF Vouchers as well :)
another use case appeared in Local Pickup Plus, as setting a pickup deadline or lead time needed time zone handling to ensure the right days on the pickup appointment calendar were selectable
the fix consisted of adopting a similar solution as Memberships to adjust a timestamp by timezone
Note: given the FW is now using PHP 5.3, and soon 5.4, perhaps in plugins we should rather switch to use native DateTime objects. We can even include Carbon in the Framework, perhaps namespaced (perhaps with Mozart? it's not a huge library anyway), to ease date-time operations with its very fluent methods. Version 1.x of the library is very stable and only requires 5.3.