Tribe__Date_Utils::build_date_object( string|DateTime|int $datetime = 'now', string|DateTimeZone|null $timezone = null, bool $with_fallback = true )

Builds a date object from a given datetime and timezone.


Parameters

$datetime

(string|DateTime|int) (Optional) A strtotime parse-able string, a DateTime object or a timestamp; defaults to now.

Default value: 'now'

$timezone

(string|DateTimeZone|null) (Optional) A timezone string, UTC offset or DateTimeZone object; defaults to the site timezone; this parameter is ignored if the $datetime parameter is a DatTime object.

Default value: null

$with_fallback

(bool) (Optional) Whether to return a DateTime object even when the date data is invalid or not; defaults to true.

Default value: true


Top ↑

Return

(DateTime|false) A DateTime object built using the specified date, time and timezone; if $with_fallback is set to false then false will be returned if a DateTime object could not be built.


Top ↑

Source

File: src/Tribe/Date_Utils.php

		public static function build_date_object( $datetime = 'now', $timezone = null, $with_fallback = true ) {
			if ( $datetime instanceof DateTime ) {
				return clone $datetime;
			}

			if ( class_exists('DateTimeImmutable') && $datetime instanceof DateTimeImmutable ) {
				// Return the mutable version of the date.
				return new DateTime( $datetime->format( 'Y-m-d H:i:s' ), $datetime->getTimezone() );
			}

			$timezone_object = null;

			try {
				// PHP 5.2 will not throw an exception but will generate an error.
				$utc = new DateTimeZone( 'UTC' );

				if ( self::is_timestamp( $datetime ) ) {
					// Timestamps timezone is always UTC.
					return new DateTime( '@' . $datetime, $utc );
				}

				$timezone_object = Tribe__Timezones::build_timezone_object( $timezone );

				set_error_handler( 'tribe_catch_and_throw' );
				$date = new DateTime( $datetime, $timezone_object );
				restore_error_handler();
			} catch ( Exception $e ) {
				if ( $timezone_object === null ) {
					$timezone_object = Tribe__Timezones::build_timezone_object( $timezone );
				}

				return $with_fallback
					? new DateTime( 'now', $timezone_object )
					: false;
			}

			return $date;
		}

Top ↑

Changelog

Changelog
Version Description
4.9.5 Introduced.