函数文档

date_i18n()

💡 云策文档标注

概述

date_i18n() 函数用于获取本地化格式的日期,基于 Unix 时间戳与时区偏移秒数之和。它类似于 PHP 的 date() 函数,但支持根据站点语言环境翻译月份和星期名称。

关键要点

  • 函数接受三个参数:$format(必需,日期格式字符串)、$timestamp_with_offset(可选,Unix 时间戳与时区偏移秒数之和,默认为 false)、$gmt(可选,是否使用 GMT 时区,仅当未提供时间戳时适用,默认为 false)。
  • 返回本地化格式的日期字符串,若语言环境指定了月份和星期名称,则优先使用本地化翻译,否则使用格式字符串。
  • 注意:该函数期望的是“WordPress 时间戳”(即时间戳与偏移之和),而非纯 Unix 时间戳;$gmt 参数在提供时间戳时通常无效。
  • 自 WordPress 5.3.0 起,推荐使用 wp_date() 函数替代 date_i18n(),以获得更好的时区处理。
  • 函数内部通过 wp_date() 实现,并包含 date_i18n 过滤器钩子,允许自定义格式化日期。

代码示例

// 获取当前本地化日期和时间,使用站点设置的格式
$datetime = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), current_time('timestamp'));

// 将 GMT 时间转换为本地时间并格式化
$dt_gmt = '2018-12-03 00:00:00';
$dt = get_date_from_gmt($dt_gmt, 'Y-m-d H:i:s');
echo date_i18n(get_option('date_format'), strtotime($dt));

// 使用 wp_date() 替代(推荐)
$date = wp_date('Y-m-d H:i:s');

注意事项

  • date_i18n() 不完全支持所有 PHP date() 格式,如简写格式;使用时需注意时区设置问题,特别是数值时区。
  • 时间戳参数应为 WordPress 时间戳(即通过 strtotime() 等生成的带偏移的时间戳),否则可能导致输出错误。
  • 在插件或主题中使用时,无需指定文本域,翻译由核心语言包提供;但格式字符串本身不会自动本地化,需通过 get_option() 或 __() 处理。

📄 原文内容

Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds.

Description

If the locale specifies the locale month and weekday, then the locale will take over the format for the date. If it isn’t, then the date format string will be used instead.

Note that due to the way WP typically generates a sum of timestamp and offset with strtotime(), it implies offset added at a current time, not at the time the timestamp represents. Storing such timestamps or calculating them differently will lead to invalid output.

Parameters

$formatstringrequired
Format to display the date.
$timestamp_with_offsetint|booloptional
A sum of Unix timestamp and timezone offset in seconds.

Default:false

$gmtbooloptional
Whether to use GMT timezone. Only applies if timestamp is not provided.

Default:false

Return

string The date, translated if locale specifies it.

Source

function date_i18n( $format, $timestamp_with_offset = false, $gmt = false ) {
	$timestamp = $timestamp_with_offset;

	// If timestamp is omitted it should be current time (summed with offset, unless `$gmt` is true).
	if ( ! is_numeric( $timestamp ) ) {
		// phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
		$timestamp = current_time( 'timestamp', $gmt );
	}

	/*
	 * This is a legacy implementation quirk that the returned timestamp is also with offset.
	 * Ideally this function should never be used to produce a timestamp.
	 */
	if ( 'U' === $format ) {
		$date = $timestamp;
	} elseif ( $gmt && false === $timestamp_with_offset ) { // Current time in UTC.
		$date = wp_date( $format, null, new DateTimeZone( 'UTC' ) );
	} elseif ( false === $timestamp_with_offset ) { // Current time in site's timezone.
		$date = wp_date( $format );
	} else {
		/*
		 * Timestamp with offset is typically produced by a UTC `strtotime()` call on an input without timezone.
		 * This is the best attempt to reverse that operation into a local time to use.
		 */
		$local_time = gmdate( 'Y-m-d H:i:s', $timestamp );
		$timezone   = wp_timezone();
		$datetime   = date_create( $local_time, $timezone );
		$date       = wp_date( $format, $datetime->getTimestamp(), $timezone );
	}

	/**
	 * Filters the date formatted based on the locale.
	 *
	 * @since 2.8.0
	 *
	 * @param string $date      Formatted date string.
	 * @param string $format    Format to display the date.
	 * @param int    $timestamp A sum of Unix timestamp and timezone offset in seconds.
	 *                          Might be without offset if input omitted timestamp but requested GMT.
	 * @param bool   $gmt       Whether to use GMT timezone. Only applies if timestamp was not provided.
	 */
	$date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt );

	return $date;
}

Hooks

apply_filters( ‘date_i18n’, string $date, string $format, int $timestamp, bool $gmt )

Filters the date formatted based on the locale.

Changelog

Version Description
5.3.0 Converted into a wrapper for wp_date() .
0.71 Introduced.

User Contributed Notes

  1. Skip to note 10 content

    The date_i18n() function basically behaves exactly like the normal PHP date() function, except that it also translates things like month names and weekdays and similar into the current locale for the site. You can replace a call to date() with a call to date_i18n(), using the same arguments that date() normally takes.

    The date_i18n() function also takes an additional argument, which should be used only if you’re specifying GMT (UTC) time and not a local time.

    The core of WordPress includes the necessary pieces to translate months and days and so forth in the core code, so this function is one translation function which does not need a text-domain when used in plugins and themes. The translations will always be included in the core language packs.

    Note that the “format”, however, is not converted to a local one if you manually specify it. If you need a localized format, then you should use get_option('date_format') if you need the format set by the user in Settings->General, and thus one of their choosing. Alternatively, you can wrap your predefined format in __() in order to allow translators to adjust the date to the proper local format. If you do so, then you should also include a translator comment, to let the translators know what the date format is referring to and where it is used, so they can convert it accurately.

  2. Skip to note 11 content

    It is important to note that date_i18n():

    1. does not have full feature parity with date(), not all formats are supported (such as shorthands);
    2. does not accept Unix timestamp (despite documented to), the expected value is “WordPress timestamp” (offset by time zone);
    3. has issues with certain timezone settings, such as numerical ones;
    4. does nothing with $gmt argument under normal circumstances;

    Any use of this function must be carefully audited for correctness, especially in regards to output of time zones.

  3. Skip to note 13 content

    $dt_gmt = '2018-12-03 00:00:00';
    
    echo 'date_i18n GMT, gmt=false: ' . date_i18n($settings_datetime_format, strtotime($dt_gmt)) . '<br>';
    echo 'date_i18n GMT, gmt=true: ' . date_i18n($settings_datetime_format, strtotime($dt_gmt), true) . '<br>';

    Result:

    date_i18n GMT, gmt=false: December 3, 2018 12:00 am
    date_i18n GMT, gmt=true: December 3, 2018 12:00 am

    The third argument has no effect if second argument was set.

    To display translated date/time based on WP settings (time zone, format). The $unixtimestamp argument must be convert from GMT like this.

    $dt_gmt = '2018-12-03 00:00:00';
    $dt = get_date_from_gmt($dt_gmt, 'Y-m-d H:i:s');// convert from GMT to local date/time based on WordPress time zone setting.
    echo date_i18n(get_option('date_format') . ' ' . get_option('time_format') . ' (P)', strtotime($dt));// get format from WordPress settings.

    The result will be:

    ธันวาคม 3, 2018 7:00 am (+07:00)

    This is based on Thai language, Bangkok time zone.

    More examples are on [moderated]

  4. Skip to note 14 content

    To get both the date and time within a single string, use date_i18n twice with a separator. At the same time, you can also retrieve the local Date and Time formats that are set within the General Settings page.

    For example, to return: ‘March 3, 2018 @ 7:18 am’ (formatted for the US, Eastern Standard Time in the General Settings page):

    $datetime = date_i18n(get_option('date_format'), current_time('timestamp')) .' @ '. date_i18n(get_option('time_format'), current_time('timestamp'));

  5. Skip to note 15 content

    A simple way to show the default format of your install date/time; and to see if it works well with i18n formatting is to pull both date and time using PHP:

    $format      = get_option('date_format') . ' ' . get_option('time_format');
    $check_stamp = date_i18n($format, current_time('timestamp'));

    Display by echoing esc_html($check_stamp);

    Result: February 25, 2022 11:36 pm

    If it shows incorrectly then you can go to your Setting > General to make good.

  6. Skip to note 18 content

    Convert another UTC time to your own timezone.
    Let us suppose you are in UTC+10 timezone And want to convert another timezone to your timezone. You can do this by adding +10 on date_18n() function.

    $converted_date = date_i18n( get_option( 'date_format' ), strtotime( '2019-06-07 00:35:32' . '+11' ) )
    Thanks