Midnight local time in WordPress-friendly php

Problem: How do I get the UNIX timestamp for midnight local time in php?

Why would I want this? To schedule a daily processing event at 00:05 every day, we might use

  wp_schedule_event( $midnight + 5 * MINUTES_IN_SECONDS, 'daily', 'hook');

This is handy for running various overnight work at a particular time of day in local time. What does “local time” mean in a WordPress instance? It means the value of date() rendered in the instance’s time zone setting.

So, to obtain $midnight, the UNIX timestamp of midnight in local time, we do this:

  private function getTodayMidnightTimestamp() {
    try {
      /* get a DateTimeZone object for WordPress's instance timezone option */
      $zone = new DateTimeZone ( get_option( 'timezone_string', 'UTC' ) );
      /* get a DateTimeImmutable object for 'today', meaning the midnight */
      $midnight = new DateTimeImmutable( 'today', $zone );
      /* convert it to a timestamp */
      return $midnight->getTimestamp();
    } catch ( Exception $ex ) {
      /* if something went wrong with the above, return midnight UTC */
      $t = time();
      return $t - ( $t % DAY_IN_SECONDS );
    }
  }

This is the way to go in a WordPress plugin. Plugin guidelines forbid the use of date_default_timezone_set() to set the default timezone, even if you set it back.

Leave a Comment