get_post_time()WP 2.0.0

Gets the time of the current post creation in the specified format. You can specify a return format (the default is Unix format). Must be used in WordPress loop.

The function gets a result for processing in php, and does not display it to the screen. Use the_time() to display the result.

Used By: get_the_time()
Hooks from the function

Return

String|Int|false. Formatted date string or Unix timestamp if $format is 'U' or 'G'. False on failure.

Usage

get_post_time( $format, $gmt, $post, $translate );
$format(string)
Format to use for retrieving the time the post was written. Accepts 'G', 'U', or PHP date format.
Default: 'U'
$gmt(true|false)
Whether to retrieve the GMT time.
Default: false
$post(int|WP_Post)
Post ID or post object.
Default: global $post object
$translate(true|false)
Whether to translate the time string.
Default: false

Examples

0

#1 Get the timestamp of the post

To get a Unix timestamp of a post adjusted for the GMT time zone (the second parameter), you can use the function like so:

$gmt_timestamp = get_post_time( 'U', true );
echo $gmt_timestamp; //> 1521992006

Changelog

Since 2.0.0 Introduced.

get_post_time() code WP 6.4.3

function get_post_time( $format = 'U', $gmt = false, $post = null, $translate = false ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$source   = ( $gmt ) ? 'gmt' : 'local';
	$datetime = get_post_datetime( $post, 'date', $source );

	if ( false === $datetime ) {
		return false;
	}

	if ( 'U' === $format || 'G' === $format ) {
		$time = $datetime->getTimestamp();

		// Returns a sum of timestamp with timezone offset. Ideally should never be used.
		if ( ! $gmt ) {
			$time += $datetime->getOffset();
		}
	} elseif ( $translate ) {
		$time = wp_date( $format, $datetime->getTimestamp(), $gmt ? new DateTimeZone( 'UTC' ) : null );
	} else {
		if ( $gmt ) {
			$datetime = $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
		}

		$time = $datetime->format( $format );
	}

	/**
	 * Filters the localized time a post was written.
	 *
	 * @since 2.6.0
	 *
	 * @param string|int $time   Formatted date string or Unix timestamp if `$format` is 'U' or 'G'.
	 * @param string     $format Format to use for retrieving the time the post was written.
	 *                           Accepts 'G', 'U', or PHP date format.
	 * @param bool       $gmt    Whether to retrieve the GMT time.
	 */
	return apply_filters( 'get_post_time', $time, $format, $gmt );
}