date_i18n

函式
date_i18n ( $format, $timestamp_with_offset = false, $gmt = false )
引數
  • (string) $format Format to display the date.
    Required:
  • (int|bool) $timestamp_with_offset Optional. A sum of Unix timestamp and timezone offset in seconds. Default false.
    Required:
    Default: false
  • (bool) $gmt Optional. Whether to use GMT timezone. Only applies if timestamp is not provided. Default false.
    Required:
    Default: false
返回值
  • (string) The date, translated if locale specifies it.
定義位置
相關方法
update_optionupdate_nagwp_update_linkvalidate_pluginwp_update_plugin
引入
0.71
棄用
-

date_i18n: 這個函式根據WordPress的日期和時間設定返回當前的日期和時間格式,並翻譯成使用者的語言。它對於在WordPress網站上以符合使用者偏好的格式顯示日期和時間很有用。

檢索本地化格式的日期,基於Unix時間戳和時區偏移量(秒)的總和。

如果locale指定了locale的月份和星期,那麼locale將接管日期的格式。如果不是這樣,那麼日期格式字串將被替代使用。

請注意,由於WP通常用`strtotime()`生成時間戳和偏移量的方式,它意味著偏移量是在_當前_時間新增的,而不是在時間戳代表的時間。儲存這樣的時間戳或以不同的方式計算它們將導致無效的輸出。

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.
	 *                          Default false.
	 */
	$date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt );

	return $date;
}

常見問題

FAQs
檢視更多 >