mysql2date()WP 0.71

Convert given date string into a different format.

  • $format should be a PHP date format string.
  • 'U' and 'G' formats will return an integer sum of timestamp with timezone offset.
  • $date is expected to be local time in MySQL format (Y-m-d H:i:s).

Historically UTC time could be passed to the function to produce Unix timestamp.

If $translate is true then the given date and format string will be passed to wp_date() translation.

Uses: wp_date()
1 time — 0.00018 sec (fast) | 50000 times — 4.42 sec (fast)

No Hooks.

Return

String|Int|false. Integer if $format is 'U' or 'G', string otherwise. False on failure.

Usage

mysql2date( $format, $date, $translate );
$format(string) (required)
Format of the date to return.
$date(string) (required)
Date string to convert.
$translate(true|false)
Whether the return date should be translated.
Default: true

Examples

0

#1 How the function works

echo mysql2date( 'd.M.Y H:i', '2015-07-24 15:23:14' ); // 24.Jul.2015 15:23

echo mysql2date( 'd-m-Y', '2020-10-25' );              // 25-10-2020
0

#2 Output the publication date of the post in the format d-m-Y:

echo mysql2date( 'd-m-Y', $post->post_date ); // 02-12-2011

Examples of formats see here.

0

#3 Don't use U, G formats to get timestamp

echo mysql2date( 'U', '2012-02-23 06:12:45' ); // 1329977565
echo mysql2date( 'G', '2012-02-23 06:12:45' ); // 1329977565

This timestamp contains Unix timestamp + current site offset, but not basic timestamp. So it is not recommended use thiscode to get UNIX timestamp.

Changelog

Since 0.71 Introduced.

mysql2date() code WP 6.1.1

function mysql2date( $format, $date, $translate = true ) {
	if ( empty( $date ) ) {
		return false;
	}

	$datetime = date_create( $date, wp_timezone() );

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

	// Returns a sum of timestamp with timezone offset. Ideally should never be used.
	if ( 'G' === $format || 'U' === $format ) {
		return $datetime->getTimestamp() + $datetime->getOffset();
	}

	if ( $translate ) {
		return wp_date( $format, $datetime->getTimestamp() );
	}

	return $datetime->format( $format );
}