get_post_time()WP 2.0.0

Gets the publication time of the post in the specified format (default is unix timestamp). Used inside the WordPress loop.

The function gets the result for processing, not outputting it to the screen. To output, use the function the_time().

Used By: get_the_time()
Hooks from the function

Returns

String|Int|false. A string of time in the specified format.

Usage

get_post_time( $d, $gmt, $post, $translate );
$d(string)
Date format. For example, j F Y will output "12 December 2010". Possible formats..
Default: 'U' (Unix timestamp)
$gmt(boolean)
Set to true to get the post time in GMT zone ($post->post_date_gmt).
Default: false
$post(int/WP_Post)
ID of the post whose time you want to get. You can pass a post object.
Default: null. object $post
$translate(boolean)
Is it necessary to translate the obtained 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.9

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 of the post.
	 *
	 * @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 date of the post.
	 *                           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 );
}