mysql2date()
云策文档标注
概述
mysql2date() 函数用于将 MySQL 格式的日期字符串转换为指定格式的日期或时间戳。它支持本地化翻译,并处理时区偏移。
关键要点
- 函数接受三个参数:$format(必需,PHP 日期格式字符串)、$date(必需,MySQL 格式的本地时间字符串,如 Y-m-d H:i:s)和 $translate(可选布尔值,默认为 true,控制是否进行本地化翻译)。
- 当 $format 为 'U' 或 'G' 时,返回整数时间戳(包含时区偏移);否则返回格式化字符串。如果转换失败,返回 false。
- 内部使用 wp_timezone() 获取时区,并通过 date_create 创建 DateTime 对象。若 $translate 为 true,则调用 wp_date() 进行本地化处理。
代码示例
// 将 MySQL 日期转换为 Unix 时间戳
echo mysql2date( 'U', '2012-02-23 06:12:45' ); // 输出: 1329977565
// 将 MySQL 日期转换为其他日期格式
echo mysql2date( 'l, F j, Y', '2012-02-23 06:12:45' ); // 输出: Thursday, February 23, 2012
原文内容
Converts given MySQL date string into a different format.
Description
$formatshould be a PHP date format string.- ‘U’ and ‘G’ formats will return an integer sum of timestamp with timezone offset.
$dateis 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() for translation.
Parameters
$formatstringrequired-
Format of the date to return.
$datestringrequired-
Date string to convert.
$translatebooloptional-
Whether the return date should be translated.
Default:
true
Source
function mysql2date( $format, $date, $translate = true ) {
if ( empty( $date ) ) {
return false;
}
$timezone = wp_timezone();
$datetime = date_create( $date, $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(), $timezone );
}
return $datetime->format( $format );
}
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 3 content
Codex
Basic Example
Convert a MySQL date to a Unix timestamp:
echo mysql2date( 'U', '2012-02-23 06:12:45' ); // 1329977565Skip to note 4 content
Codex
MySQL date conversion
Convert a MySQL date to another date format:
echo mysql2date( 'l, F j, Y', '2012-02-23 06:12:45' ) // Thursday, February 23, 2012