1

Date field data won't always correspond to UTC. From a user perspective, these dates are assumed to be in the user's timezone. However, it is currently not possible to store dates in timezones other than UTC, at least until Add ability to select a timezone for datetime field gets in.

So when comparing these fields to the current time, the timezones won't match because the current time is in the local timezone and the field data is in UTC. We therefore need to adjust the current time to match the incorrect date field timezone (or vice versa).

What's a good solution for this?

  • To whoever downvoted this: Please only downvote questions if you can provide feedback. This will help us ask better questions. Thanks. – colan Feb 26 '18 at 14:04
2

I've developed a method to handle the conversion, thanks to help from another answer to another question. It requires a patch from Add DateTimePlus::getPhpDateTime() for situations that require a DateTimeInterface to work, however.

  /**
   * Fetches the current time adjusted for comparing to non-UTC date fields.
   *
   * Date field data won't always correspond to UTC. From a user perspective, 
   * these dates are assumed to be in the user's timezone.  However, it is
   * currently not possible to store dates in timezones other than UTC. So when
   * comparing these fields to the current time, the timezones won't match
   * because one is the local timezone and the other is in UTC.  We therefore
   * need to adjust the current time to match the incorrect date field timezone.
   *
   * @param Drupal\Core\Datetime\DrupalDateTime $date_time
   *   The date-time object fetched from a Date field (e.g. field_date->date).
   */
  protected static function getCurrentTimeForComparingToDateFieldIncorrectlyStoredInUtc(DrupalDateTime $date_time) {
    $current_time = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
    $userTimezone = new \DateTimeZone(drupal_get_user_timezone());
    $timezone_offset = $userTimezone->getOffset($date_time->getPhpDateTime());
    $time_interval = \DateInterval::createFromDateString($timezone_offset . ' seconds');
    $current_time->add($time_interval);
    return $current_time;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.