WC_API_Server::format_datetime()publicWC 2.1

Format a unix timestamp or MySQL datetime into an RFC3339 datetime

Method of the class: WC_API_Server{}

No Hooks.

Return

String. RFC3339 datetime

Usage

$WC_API_Server = new WC_API_Server();
$WC_API_Server->format_datetime( $timestamp, $convert_to_utc, $convert_to_gmt );
$timestamp(int|string) (required)
unix timestamp or MySQL datetime
$convert_to_utc(true|false)
-
Default: false
$convert_to_gmt(true|false)
Use GMT timezone.
Default: false

Changelog

Since 2.1 Introduced.

WC_API_Server::format_datetime() code WC 8.7.0

public function format_datetime( $timestamp, $convert_to_utc = false, $convert_to_gmt = false ) {
	if ( $convert_to_gmt ) {
		if ( is_numeric( $timestamp ) ) {
			$timestamp = date( 'Y-m-d H:i:s', $timestamp );
		}

		$timestamp = get_gmt_from_date( $timestamp );
	}

	if ( $convert_to_utc ) {
		$timezone = new DateTimeZone( wc_timezone_string() );
	} else {
		$timezone = new DateTimeZone( 'UTC' );
	}

	try {

		if ( is_numeric( $timestamp ) ) {
			$date = new DateTime( "@{$timestamp}" );
		} else {
			$date = new DateTime( $timestamp, $timezone );
		}

		// convert to UTC by adjusting the time based on the offset of the site's timezone
		if ( $convert_to_utc ) {
			$date->modify( -1 * $date->getOffset() . ' seconds' );
		}
	} catch ( Exception $e ) {

		$date = new DateTime( '@0' );
	}

	return $date->format( 'Y-m-d\TH:i:s\Z' );
}