8.4 中文镜像

MySQL 8.4 参考手册 · 中文镜像

正文为中文,英文原文默认隐藏。点击任意中文段落即可展开 / 收起对应英文原文。

打开官方英文原文 ↗

译文由机器翻译生成,仅供理解参考;有疑问请以官方英文原文为准。

MySQL 8.4 参考手册 / 14 函数和运算符 / 14.7 日期和时间函数
中文点击中文段落可显示 / 隐藏英文原文本页译文覆盖 67%

14.7 日期和时间函数14.7 Date and Time Functions

本节介绍可用于操作时间值的函数。有关每种日期和时间类型的值范围以及可指定值的有效格式的描述,请参见 第 13.2 节,“日期和时间数据类型”。This section describes the functions that can be used to manipulate temporal values. See Section 13.2, “Date and Time Data Types”, for a description of the range of values each date and time type has and the valid formats in which values may be specified.

表 14.11 日期和时间函数Table 14.11 Date and Time Functions

名称Name 说明Description
ADDDATE() 将时间值(间隔)添加到日期值Add time values (intervals) to a date value
ADDTIME() 添加时间Add time
CONVERT_TZ() 将一个时区转换为另一个时区Convert from one time zone to another
CURDATE() 返回当前日期Return the current date
CURRENT_DATE(), CURRENT_DATE CURDATE() 的同义词Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME CURTIME() 的同义词Synonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP NOW() 的同义词Synonyms for NOW()
CURTIME() 返回当前时间Return the current time
DATE() 提取日期或日期时间表达式中的日期部分Extract the date part of a date or datetime expression
DATE_ADD() 将时间值(间隔)添加到日期值Add time values (intervals) to a date value
DATE_FORMAT() 按指定格式显示日期Format date as specified
DATE_SUB() 从日期中减去时间值(间隔)Subtract a time value (interval) from a date
DATEDIFF() 相减两个日期Subtract two dates
DAY() DAYOFMONTH() 的同义词Synonym for DAYOFMONTH()
DAYNAME() 返回星期几的名称Return the name of the weekday
DAYOFMONTH() 返回月份中的日期(0-31)Return the day of the month (0-31)
DAYOFWEEK() 返回参数的星期索引Return the weekday index of the argument
DAYOFYEAR() 返回一年中的第几天(1-366)Return the day of the year (1-366)
EXTRACT() 提取日期的一部分Extract part of a date
FROM_DAYS() 将天数转换为日期Convert a day number to a date
FROM_UNIXTIME() 将 Unix 时间戳格式化为日期Format Unix timestamp as a date
GET_FORMAT() 返回日期格式字符串Return a date format string
HOUR() 提取小时Extract the hour
LAST_DAY 返回参数月份的最后一天Return the last day of the month for the argument
LOCALTIME(), LOCALTIME NOW() 的同义词Synonym for NOW()
LOCALTIMESTAMP, LOCALTIMESTAMP() NOW() 的同义词Synonym for NOW()
MAKEDATE() 根据年份和一年中的天数创建日期Create a date from the year and day of year
MAKETIME() 根据小时、分钟、秒创建时间Create time from hour, minute, second
MICROSECOND() 返回参数的微秒数Return the microseconds from argument
MINUTE() 从参数中返回分钟Return the minute from the argument
MONTH() 从传递的日期中返回月份Return the month from the date passed
MONTHNAME() 返回月份的名称Return the name of the month
NOW() 返回当前日期和时间Return the current date and time
PERIOD_ADD() 在年月后添加句号Add a period to a year-month
PERIOD_DIFF() 返回期间之间的月份数Return the number of months between periods
QUARTER() 从日期参数返回季度Return the quarter from a date argument
SEC_TO_TIME() 将秒转换为“hh:mm:ss”格式Converts seconds to 'hh:mm:ss' format
SECOND() 返回第二个(0-59)Return the second (0-59)
STR_TO_DATE() 将字符串转换为日期Convert a string to a date
SUBDATE() 当使用三个参数调用时,DATE_SUB() 的同义词Synonym for DATE_SUB() when invoked with three arguments
SUBTIME() 减去次数Subtract times
SYSDATE() 返回函数执行的时间Return the time at which the function executes
TIME() 提取传入表达式的时间部分Extract the time portion of the expression passed
TIME_FORMAT() 格式化为时间Format as time
TIME_TO_SEC() 将参数转换为秒后返回Return the argument converted to seconds
TIMEDIFF() 减去时间Subtract time
TIMESTAMP()TIMESTAMP() 当只有一个参数时,此函数返回日期或日期时间表达式;当有两个参数时,返回参数的和With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments
TIMESTAMPADD() 向日期时间表达式添加一个时间间隔Add an interval to a datetime expression
TIMESTAMPDIFF() 返回两个日期时间表达式的差值,使用指定的单位Return the difference of two datetime expressions, using the units specified
TO_DAYS() 将日期参数转换为天数Return the date argument converted to days
TO_SECONDS() 返回转换为自公元 0 年以来的秒数的日期或日期时间参数Return the date or datetime argument converted to seconds since Year 0
UNIX_TIMESTAMP() 返回 Unix 时间戳Return a Unix timestamp
UTC_DATE() 返回当前的 UTC 日期Return the current UTC date
UTC_TIME() 返回当前的 UTC 时间Return the current UTC time
UTC_TIMESTAMP() 返回当前的 UTC 日期和时间Return the current UTC date and time
WEEK() 返回周数Return the week number
WEEKDAY() 返回星期索引Return the weekday index
WEEKOFYEAR() 返回日期的日历周(1-53)Return the calendar week of the date (1-53)
YEAR() 返回年份Return the year
YEARWEEK() 返回年份和周数Return the year and week

这是一个使用日期函数的示例。以下查询选择所有 date_col 值在过去 30 天内的行:Here is an example that uses date functions. The following query selects all rows with a date_col value from within the last 30 days:

mysql> SELECT something FROM tbl_name
    -> WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= date_col;

该查询还会选择日期位于未来的行。The query also selects rows with dates that lie in the future.

期望日期值的函数通常接受日期时间值并忽略时间部分。期望时间值的函数通常接受日期时间值并忽略日期部分。Functions that expect date values usually accept datetime values and ignore the time part. Functions that expect time values usually accept datetime values and ignore the date part.

返回当前日期或时间的函数在每个查询中只在查询执行开始时评估一次。这意味着在单个查询中多次引用诸如 NOW() 的函数总是产生相同的结果。(就我们的目的而言,单个查询也包括对存储程序(存储例程、触发器或事件)的调用以及该程序调用的所有子程序。)这一原则同样适用于 CURDATE()、CURTIME()、UTC_DATE()、UTC_TIME()、UTC_TIMESTAMP(),以及它们的任何同义词。Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query always produce the same result. (For our purposes, a single query also includes a call to a stored program (stored routine, trigger, or event) and all subprograms called by that program.) This principle also applies to CURDATE(), CURTIME(), UTC_DATE(), UTC_TIME(), UTC_TIMESTAMP(), and to any of their synonyms.

CURRENT_TIMESTAMP()、CURRENT_TIME()、CURRENT_DATE() 和 FROM_UNIXTIME() 函数返回当前会话时区的值,该时区可以通过系统变量 time_zone 的会话值获取。此外,UNIX_TIMESTAMP() 假定其参数是会话时区中的一个日期时间值。参见 第 7.1.15 节,“MySQL 服务器时区支持”。The CURRENT_TIMESTAMP(), CURRENT_TIME(), CURRENT_DATE(), and FROM_UNIXTIME() functions return values in the current session time zone, which is available as the session value of the time_zone system variable. In addition, UNIX_TIMESTAMP() assumes that its argument is a datetime value in the session time zone. See Section 7.1.15, “MySQL Server Time Zone Support”.

可用于零“零”日期或不完全日期,'2001-11-00'如,而另一些则不行。提取日期部分的函数通常适用于不完整日期,因此在你本可能预期非零值时返回 0。例如:Some date functions can be used with “zero” dates or incomplete dates such as '2001-11-00', whereas others cannot. Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a nonzero value. For example:

mysql> SELECT DAYOFMONTH('2001-11-00'), MONTH('2005-00-00');
        -> 0, 0

其他函数则需要完整的日期,并且对于不完整日期会返回 NULL。这些函数包括执行日期算术或将日期部分映射到名称的函数。例如:Other functions expect complete dates and return NULL for incomplete dates. These include functions that perform date arithmetic or that map parts of dates to names. For example:

mysql> SELECT DATE_ADD('2006-05-00',INTERVAL 1 DAY);
        -> NULL
mysql> SELECT DAYNAME('2006-05-00');
        -> NULL

当将 DATE() 函数的值作为参数传入时,一些函数是严格的,并且会拒绝日部分为零的不完整日期:CONVERT_TZ()、DATE_ADD()、DATE_SUB()、DAYOFYEAR()、TIMESTAMPDIFF()、TO_DAYS()、TO_SECONDS()、WEEK()、WEEKDAY()、WEEKOFYEAR()、YEARWEEK()。Several functions are strict when passed a DATE() function value as their argument and reject incomplete dates with a day part of zero: CONVERT_TZ(), DATE_ADD(), DATE_SUB(), DAYOFYEAR(), TIMESTAMPDIFF(), TO_DAYS(), TO_SECONDS(), WEEK(), WEEKDAY(), WEEKOFYEAR(), YEARWEEK().

支持 TIME、DATETIME 和 TIMESTAMP 值的分数秒,精确到微秒。接受时间参数的函数可以接受带有分数秒的值。时间函数的返回值会根据需要包含分数秒。Fractional seconds for TIME, DATETIME, and TIMESTAMP values are supported, with up to microsecond precision. Functions that take temporal arguments accept values with fractional seconds. Return values from temporal functions include fractional seconds as appropriate.

  • ADDDATE(date,INTERVAL expr unit), ADDDATE(date,days)

    当第二个参数使用 INTERVAL 形式调用时,ADDDATE() 是 DATE_ADD() 的同义词。相关函数 SUBDATE() 是 DATE_SUB() 的同义词。有关 INTERVAL unit 参数的信息,请参见 时间间隔。When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see Temporal Intervals.

    mysql> SELECT DATE_ADD('2008-01-02', INTERVAL 31 DAY);
            -> '2008-02-02'
    mysql> SELECT ADDDATE('2008-01-02', INTERVAL 31 DAY);
            -> '2008-02-02'
    

    当使用第二个参数的days形式调用时,MySQL 会将其视为要添加到expr的天数整数。When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr.

    mysql> SELECT ADDDATE('2008-01-02', 31);
            -> '2008-02-02'
    

    如果date或days为NULL,则此函数返回NULL。This function returns NULL if date or days is NULL.

  • ADDTIME(expr1,expr2)

    ADDTIME() 将 expr2 加到 expr1 并返回结果。expr1 是时间或日期时间表达式,expr2 是时间表达式。如果 expr1 或 expr2 为 NULL,则返回 NULL。ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime expression, and expr2 is a time expression. Returns NULL if expr1or expr2 is NULL.

    该函数和 SUBTIME() 函数的返回类型如下确定:The return type of this function and of the SUBTIME() function is determined as follows:

    • 如果第一个参数是动态参数(例如在预处理语句中),返回类型为 TIME。If the first argument is a dynamic parameter (such as in a prepared statement), the return type is TIME.

    • 否则,函数的解析类型由第一个参数的解析类型推导得出。Otherwise, the resolved type of the function is derived from the resolved type of the first argument.

    mysql> SELECT ADDTIME('2007-12-31 23:59:59.999999', '1 1:1:1.000002');
            -> '2008-01-02 01:01:01.000001'
    mysql> SELECT ADDTIME('01:00:00.999999', '02:00:00.999998');
            -> '03:00:01.999997'
    
  • CONVERT_TZ(dt,from_tz,to_tz)

    CONVERT_TZ() 将日期时间值 dt 从由 from_tz 指定的时区转换为由 to_tz 指定的时区,并返回结果值。时区的指定方式如 第 7.1.15 节,“MySQL 服务器时区支持” 所述。如果任何参数无效,或任何参数为 NULL,则此函数返回 NULL。CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. Time zones are specified as described in Section 7.1.15, “MySQL Server Time Zone Support”. This function returns NULL if any of the arguments are invalid, or if any of them are NULL.

    在 32 位平台上,此函数支持的值范围与TIMESTAMP类型相同(有关范围信息,请参见第 13.2.1 节,“日期和时间数据类型语法”)。在 64 位平台上,支持的最大值为'3001-01-18 23:59:59.999999' UTC。On 32-bit platforms, the supported range of values for this function is the same as for the TIMESTAMP type (see Section 13.2.1, “Date and Time Data Type Syntax”, for range information). On 64-bit platforms, the maximum supported value is '3001-01-18 23:59:59.999999' UTC.

    无论平台或 MySQL 版本如何,如果从from_tz转换为 UTC 时值超出支持范围,则不会进行转换。Regardless of platform or MySQL version, if the value falls out of the supported range when converted from from_tz to UTC, no conversion occurs.

    mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
            -> '2004-01-01 13:00:00'
    mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');
            -> '2004-01-01 22:00:00'
    
    Note

    要使用诸如 'MET' 或 'Europe/Amsterdam' 这样的命名时区,必须正确设置时区表。有关说明,请参见 第 7.1.15 节,“MySQL 服务器时区支持”。To use named time zones such as 'MET' or 'Europe/Amsterdam', the time zone tables must be properly set up. For instructions, see Section 7.1.15, “MySQL Server Time Zone Support”.

  • CURDATE()

    根据函数是在字符串还是数字上下文中使用,返回当前日期,格式为'YYYY-MM-DD'或YYYYMMDD。Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in string or numeric context.

    mysql> SELECT CURDATE();
            -> '2008-06-13'
    mysql> SELECT CURDATE() + 0;
            -> 20080613
    
  • CURRENT_DATE, CURRENT_DATE()

    CURRENT_DATE 和 CURRENT_DATE() 是 CURDATE() 的同义词。CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE().

  • CURRENT_TIME, CURRENT_TIME([fsp])

    CURRENT_TIME 和 CURRENT_TIME() 是 CURTIME() 的同义词。CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME().

  • CURRENT_TIMESTAMP, CURRENT_TIMESTAMP([fsp])

    CURRENT_TIMESTAMP 和 CURRENT_TIMESTAMP() 是 NOW() 的同义词。CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW().

  • CURTIME([fsp])

    根据函数在字符串或数字上下文中使用的不同,返回当前时间,格式为'hh:mm:ss'或hhmmss。该值以会话时区表示。Returns the current time as a value in 'hh:mm:ss' or hhmmss format, depending on whether the function is used in string or numeric context. The value is expressed in the session time zone.

    如果提供了fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If the fsp argument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.

    mysql> SELECT CURTIME();
    +-----------+
    | CURTIME() |
    +-----------+
    | 19:25:37  |
    +-----------+
    
    mysql> SELECT CURTIME() + 0;
    +---------------+
    | CURTIME() + 0 |
    +---------------+
    |        192537 |
    +---------------+
    
    mysql> SELECT CURTIME(3);
    +--------------+
    | CURTIME(3)   |
    +--------------+
    | 19:25:37.840 |
    +--------------+
    
  • DATE(expr)

    提取日期或日期时间表达式expr的日期部分。如果expr为NULL,则返回NULL。Extracts the date part of the date or datetime expression expr. Returns NULL if expr is NULL.

    mysql> SELECT DATE('2003-12-31 01:02:03');
            -> '2003-12-31'
    
  • DATEDIFF(expr1,expr2)

    DATEDIFF() 返回以天数表示的 expr1 − expr2,从一个日期到另一个日期。expr1 和 expr2 是日期或日期时间表达式。计算中仅使用值的日期部分。DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.

    mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
            -> 1
    mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
            -> -31
    

    如果 expr1 或 expr2 为 NULL,则该函数返回 NULL。This function returns NULL if expr1 or expr2 is NULL.

  • DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL expr unit)

    这些函数用于日期运算。date 参数指定起始日期或日期时间值。expr 是一个表达式,指定要加到或减去起始日期的时间间隔值。expr 被作为字符串求值;它可以以 - 开头表示负时间间隔。unit 是一个关键字,指示表达式应按照哪种单位来解释。These functions perform date arithmetic. The date argument specifies the starting date or datetime value. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is evaluated as a string; it may start with a - for negative intervals. unit is a keyword indicating the units in which the expression should be interpreted.

    有关时间间隔语法的更多信息,包括完整的unit说明符列表、每个unit值的expr参数的期望形式,以及时间运算中运算数解释的规则,请参见时间间隔。For more information about temporal interval syntax, including a full list of unit specifiers, the expected form of the expr argument for each unit value, and rules for operand interpretation in temporal arithmetic, see Temporal Intervals.

    返回值取决于参数:The return value depends on the arguments:

    • 如果 date 为 NULL,函数返回 NULL。If date is NULL, the function returns NULL.

    • DATE如果参数date是DATE值且计算仅涉及YEAR, MONTH,以及DAY部分(即不包含时间部分)。DATE if the date argument is a DATE value and your calculations involve only YEAR, MONTH, and DAY parts (that is, no time parts).

    • TIME 如果 date 参数是 TIME 值,并且计算仅涉及 HOURS、MINUTES 和 SECONDS 部分(即不涉及日期部分)。TIME if the date argument is a TIME value and the calculations involve only HOURS, MINUTES, and SECONDS parts (that is, no date parts).

    • DATETIME 如果第一个参数是 DATETIME(或 TIMESTAMP)值,或者如果第一个参数是 DATE 且 unit 值使用 HOURS、MINUTES 或 SECONDS,或者如果第一个参数是 TIME 类型且 unit 值使用 YEAR、MONTH 或 DAY。DATETIME if the first argument is a DATETIME (or TIMESTAMP) value, or if the first argument is a DATE and the unit value uses HOURS, MINUTES, or SECONDS, or if the first argument is of type TIME and the unit value uses YEAR, MONTH, or DAY.

    • 如果第一个参数是动态参数(例如,预准备语句的参数),当第二个参数是仅包含YEAR、MONTH或DAY值的间隔时,其解析类型为DATE;否则,其类型为DATETIME。If the first argument is a dynamic parameter (for example, of a prepared statement), its resolved type is DATE if the second argument is an interval that contains some combination of YEAR, MONTH, or DAY values only; otherwise, its type is DATETIME.

    • 否则为字符串(类型 VARCHAR)。String otherwise (type VARCHAR).

    为了确保结果是 DATETIME,您可以使用 CAST() 将第一个参数转换为 DATETIME。To ensure that the result is DATETIME, you can use CAST() to convert the first argument to DATETIME.

    mysql> SELECT DATE_ADD('2018-05-01',INTERVAL 1 DAY);
            -> '2018-05-02'
    mysql> SELECT DATE_SUB('2018-05-01',INTERVAL 1 YEAR);
            -> '2017-05-01'
    mysql> SELECT DATE_ADD('2020-12-31 23:59:59',
        ->                 INTERVAL 1 SECOND);
            -> '2021-01-01 00:00:00'
    mysql> SELECT DATE_ADD('2018-12-31 23:59:59',
        ->                 INTERVAL 1 DAY);
            -> '2019-01-01 23:59:59'
    mysql> SELECT DATE_ADD('2100-12-31 23:59:59',
        ->                 INTERVAL '1:1' MINUTE_SECOND);
            -> '2101-01-01 00:01:00'
    mysql> SELECT DATE_SUB('2025-01-01 00:00:00',
        ->                 INTERVAL '1 1:1:1' DAY_SECOND);
            -> '2024-12-30 22:58:59'
    mysql> SELECT DATE_ADD('1900-01-01 00:00:00',
        ->                 INTERVAL '-1 10' DAY_HOUR);
            -> '1899-12-30 14:00:00'
    mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);
            -> '1997-12-02'
    mysql> SELECT DATE_ADD('1992-12-31 23:59:59.000002',
        ->            INTERVAL '1.999999' SECOND_MICROSECOND);
            -> '1993-01-01 00:00:01.000001'
    

    当向 DATE 或 DATETIME 值添加 MONTH 间隔时,如果得到的日期包含该月不存在的日期,则该日会调整为该月的最后一天,如下所示:When adding a MONTH interval to a DATE or DATETIME value, and the resulting date includes a day that does not exist in the given month, the day is adjusted to the last day of the month, as shown here:

    mysql> SELECT DATE_ADD('2024-03-30', INTERVAL 1 MONTH) AS d1, 
         >        DATE_ADD('2024-03-31', INTERVAL 1 MONTH) AS d2;
    +------------+------------+
    | d1         | d2         |
    +------------+------------+
    | 2024-04-30 | 2024-04-30 |
    +------------+------------+
    1 row in set (0.00 sec)
    
  • DATE_FORMAT(date,format)

    根据format字符串格式化date值。如果任一参数为NULL,函数返回NULL。Formats the date value according to the format string. If either argument is NULL, the function returns NULL.

    下表中显示的格式说明符可以在format字符串中使用。格式说明符字符前必须加%字符。该说明符也适用于其他函数:STR_TO_DATE()、TIME_FORMAT()、UNIX_TIMESTAMP()。The specifiers shown in the following table may be used in the format string. The % character is required before format specifier characters. The specifiers apply to other functions as well: STR_TO_DATE(), TIME_FORMAT(), UNIX_TIMESTAMP().

    指定符Specifier 说明Description
    %a 星期的缩写名(Sun..Sat)Abbreviated weekday name (Sun..Sat)
    %b 月份缩写(Jan..Dec)Abbreviated month name (Jan..Dec)
    %c 月份,数字(0..12)Month, numeric (0..12)
    %D 带英文后缀的月份中的日期(0th, 1st, 2nd, 3rd, …)Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
    %d 月份中的日期,数字(00..31)Day of the month, numeric (00..31)
    %e 月份中的日期,数字(0..31)Day of the month, numeric (0..31)
    %f 微秒 (000000..999999)Microseconds (000000..999999)
    %H 小时 (00..23)Hour (00..23)
    %h 小时 (01..12)Hour (01..12)
    %I 小时 (01..12)Hour (01..12)
    %i 分钟,数字形式 (00..59)Minutes, numeric (00..59)
    %j 一年中的第几天 (001..366)Day of year (001..366)
    %k 小时 (0..23)Hour (0..23)
    %l 小时 (1..12)Hour (1..12)
    %M 月份名称 (January..December)Month name (January..December)
    %m 月份,数字表示 (00..12)Month, numeric (00..12)
    %p AM 或 PMAM or PM
    %r 时间,12 小时制 (hh:mm:ss 后跟 AM 或 PM)Time, 12-hour (hh:mm:ss followed by AM or PM)
    %S 秒 (00..59)Seconds (00..59)
    %s 秒 (00..59)Seconds (00..59)
    %T 时间,24 小时制 (hh:mm:ss)Time, 24-hour (hh:mm:ss)
    %U 周数(00..53),以星期天为一周的第一天;WEEK() 模式 0Week (00..53), where Sunday is the first day of the week; WEEK() mode 0
    %u 周数(00..53),以星期一为一周的第一天;WEEK() 模式 1Week (00..53), where Monday is the first day of the week; WEEK() mode 1
    %V 周数(01..53),以星期天为一周的第一天;WEEK() 模式 2;与 %X 一起使用Week (01..53), where Sunday is the first day of the week; WEEK() mode 2; used with %X
    %v 周(01..53),星期一为一周的第一天;WEEK() 模式 3;与 %x 一起使用Week (01..53), where Monday is the first day of the week; WEEK() mode 3; used with %x
    %W 星期名称(Sunday..Saturday)Weekday name (Sunday..Saturday)
    %w 星期中的日子(0=星期日..6=星期六)Day of the week (0=Sunday..6=Saturday)
    %X 以星期日为一周第一天的年份,数字表示,四位数;与 %V 一起使用Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
    %x 以星期一为一周第一天的年份,数字表示,四位数;与 %v 一起使用Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
    %Y 年份,数字,四位数Year, numeric, four digits
    %y 年份,数字(两位数)Year, numeric (two digits)
    %% 一个字面上的 % 字符A literal % character
    %x x,适用于上面未列出的任何 “x”x, for any “x” not listed above

    月份和日期说明符的范围从零开始,因为 MySQL 允许存储不完整的日期,例如 '2014-00-00'。Ranges for the month and day specifiers begin with zero due to the fact that MySQL permits the storing of incomplete dates such as '2014-00-00'.

    用于日期和月份名称及缩写的语言由 lc_time_names 系统变量的值控制(第 12.16 节,“MySQL 服务器区域设置支持”)。The language used for day and month names and abbreviations is controlled by the value of the lc_time_names system variable (Section 12.16, “MySQL Server Locale Support”).

    对于 %U、%u、%V 和 %v 说明符,请参阅 WEEK() 函数的描述,以获取关于模式值的信息。模式会影响周编号的方式。For the %U, %u, %V, and %v specifiers, see the description of the WEEK() function for information about the mode values. The mode affects how week numbering occurs.

    DATE_FORMAT() 返回一个字符串,其字符集和排序规则由 character_set_connection 和 collation_connection 给出,这样它就可以返回包含非 ASCII 字符的月份和星期名称。DATE_FORMAT() returns a string with a character set and collation given by character_set_connection and collation_connection so that it can return month and weekday names containing non-ASCII characters.

    mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');
            -> 'Sunday October 2009'
    mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');
            -> '22:23:00'
    mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00',
        ->                 '%D %y %a %d %m %b %j');
            -> '4th 00 Thu 04 10 Oct 277'
    mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
        ->                 '%H %k %I %r %T %S %w');
            -> '22 22 10 10:23:00 PM 22:23:00 00 6'
    mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
            -> '1998 52'
    mysql> SELECT DATE_FORMAT('2006-06-00', '%d');
            -> '00'
    
  • DATE_SUB(date,INTERVAL expr unit)DATE_SUB(date,INTERVAL expr unit)

    请参阅 DATE_ADD() 的描述。See the description for DATE_ADD().

  • DAY(date)DAY(date)

    DAY() 是 DAYOFMONTH() 的同义词。DAY() is a synonym for DAYOFMONTH().

  • DAYNAME(date)DAYNAME(date)

    返回 date 的星期名称。名称使用的语言由 lc_time_names 系统变量的值控制(见 第 12.16 节,“MySQL 服务器区域设置支持”)。如果 date 为 NULL,则返回 NULL。Returns the name of the weekday for date. The language used for the name is controlled by the value of the lc_time_names system variable (see Section 12.16, “MySQL Server Locale Support”). Returns NULL if date is NULL.

    mysql> SELECT DAYNAME('2007-02-03');
            -> 'Saturday'
    
  • DAYOFMONTH(date)DAYOFMONTH(date)

    返回 date 的月份中的日,范围为 1 到 31,对于像 '0000-00-00' 或 '2008-00-00' 这样日部分为零的日期返回 0。如果 date 为 NULL,则返回 NULL。Returns the day of the month for date, in the range 1 to 31, or 0 for dates such as '0000-00-00' or '2008-00-00' that have a zero day part. Returns NULL if date is NULL.

    mysql> SELECT DAYOFMONTH('2007-02-03');
            -> 3
    
  • DAYOFWEEK(date)DAYOFWEEK(date)

    返回 date 的星期索引(1 = 星期日,2 = 星期一,……,7 = 星期六)。这些索引值对应 ODBC 标准。如果 date 为 NULL,则返回 NULL。Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard. Returns NULL if date is NULL.

    mysql> SELECT DAYOFWEEK('2007-02-03');
            -> 7
    
  • DAYOFYEAR(date)DAYOFYEAR(date)

    返回 date 在一年中的第几天,范围为 1 到 366。如果 date 为 NULL,则返回 NULL。Returns the day of the year for date, in the range 1 to 366. Returns NULL if date is NULL.

    mysql> SELECT DAYOFYEAR('2007-02-03');
            -> 34
    
  • EXTRACT(unit FROM date)EXTRACT(unit FROM date)

    EXTRACT() 函数使用与 DATE_ADD() 或 DATE_SUB() 相同类型的 unit 指定符,但它从日期中提取部分内容,而不是执行日期运算。有关 unit 参数的信息,请参见 时间间隔。如果 date 为 NULL,则返回 NULL。The EXTRACT() function uses the same kinds of unit specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic. For information on the unit argument, see Temporal Intervals. Returns NULL if date is NULL.

    mysql> SELECT EXTRACT(YEAR FROM '2019-07-02');
            -> 2019
    mysql> SELECT EXTRACT(YEAR_MONTH FROM '2019-07-02 01:02:03');
            -> 201907
    mysql> SELECT EXTRACT(DAY_MINUTE FROM '2019-07-02 01:02:03');
            -> 20102
    mysql> SELECT EXTRACT(MICROSECOND
        ->                FROM '2003-01-02 10:30:00.000123');
            -> 123
    
  • FROM_DAYS(N)

    给定一个天数 N,返回一个 DATE 值。如果 N 为 NULL,则返回 NULL。Given a day number N, returns a DATE value. Returns NULL if N is NULL.

    mysql> SELECT FROM_DAYS(730669);
            -> '2000-07-03'
    

    在处理旧日期时使用 FROM_DAYS() 时请谨慎。它不适用于格里高利历(1582 年)之前的日期值。详见 第 13.2.7 节,“MySQL 使用的历法”。Use FROM_DAYS() with caution on old dates. It is not intended for use with values that precede the advent of the Gregorian calendar (1582). See Section 13.2.7, “What Calendar Is Used By MySQL?”.

  • FROM_UNIXTIME(unix_timestamp[,format])FROM_UNIXTIME(unix_timestamp[,format])

    返回 unix_timestamp 的日期时间或字符字符串表示。返回的值使用会话时区表示。(客户端可以按照 第 7.1.15 节,“MySQL 服务器时区支持” 中的说明设置会话时区。)unix_timestamp 是一个内部时间戳值,表示自 '1970-01-01 00:00:00' UTC 起的秒数,例如由 UNIX_TIMESTAMP() 函数生成的值。Returns a representation of unix_timestamp as a datetime or character string value. The value returned is expressed using the session time zone. (Clients can set the session time zone as described in Section 7.1.15, “MySQL Server Time Zone Support”.) unix_timestamp is an internal timestamp value representing seconds since '1970-01-01 00:00:00' UTC, such as produced by the UNIX_TIMESTAMP() function.

    如果省略 format,此函数将返回一个 DATETIME 值。If format is omitted, this function returns a DATETIME value.

    如果 unix_timestamp 或 format 为 NULL,此函数将返回 NULL。If unix_timestamp or format is NULL, this function returns NULL.

    如果unix_timestamp是整数,则DATETIME的小数秒精度为零。当unix_timestamp是小数值时,DATETIME的小数秒精度与小数值的精度相同,最多为 6。当unix_timestamp是浮点数时,datetime 的小数秒精度为 6。If unix_timestamp is an integer, the fractional seconds precision of the DATETIME is zero. When unix_timestamp is a decimal value, the fractional seconds precision of the DATETIME is the same as the precision of the decimal value, up to a maximum of 6. When unix_timestamp is a floating point number, the fractional seconds precision of the datetime is 6.

    在 32 位平台上,unix_timestamp 的最大有效值是 2147483647.999999,对应返回 '2038-01-19 03:14:07.999999' UTC。在 64 位平台上,有效最大值是 32536771199.999999,对应返回 '3001-01-18 23:59:59.999999' UTC。无论平台或版本如何,若 unix_timestamp 的值超过有效最大值,均返回 0。On 32-bit platforms, the maximum useful value for unix_timestamp is 2147483647.999999, which returns '2038-01-19 03:14:07.999999' UTC. On 64-bit platforms, the effective maximum is 32536771199.999999, which returns '3001-01-18 23:59:59.999999' UTC. Regardless of platform or version, a greater value for unix_timestamp than the effective maximum returns 0.

    format 用于按照用于 DATE_FORMAT() 函数的格式字符串的相同方式格式化结果。如果提供了 format,返回的值是 VARCHAR。format is used to format the result in the same way as the format string used for the DATE_FORMAT() function. If format is supplied, the value returned is a VARCHAR.

    mysql> SELECT FROM_UNIXTIME(1447430881);
            -> '2015-11-13 10:08:01'
    mysql> SELECT FROM_UNIXTIME(1447430881) + 0;
            -> 20151113100801
    mysql> SELECT FROM_UNIXTIME(1447430881,
        ->                      '%Y %D %M %h:%i:%s %x');
            -> '2015 13th November 10:08:01 2015'
    
    Note

    如果你使用 UNIX_TIMESTAMP() 和 FROM_UNIXTIME() 在非 UTC 时区值与 Unix 时间戳值之间进行转换,转换是有损的,因为这种映射在两个方向上都不是一对一的。详情请参阅 UNIX_TIMESTAMP() 函数的描述。If you use UNIX_TIMESTAMP() and FROM_UNIXTIME() to convert between values in a non-UTC time zone and Unix timestamp values, the conversion is lossy because the mapping is not one-to-one in both directions. For details, see the description of the UNIX_TIMESTAMP() function.

  • GET_FORMAT({DATE|TIME|DATETIME}, {'EUR'|'USA'|'JIS'|'ISO'|'INTERNAL'})

    返回一个格式字符串。此函数在与 DATE_FORMAT() 和 STR_TO_DATE() 函数结合使用时非常有用。Returns a format string. This function is useful in combination with the DATE_FORMAT() and the STR_TO_DATE() functions.

    如果 format 为 NULL,则此函数返回 NULL。If format is NULL, this function returns NULL.

    第一个和第二个参数的可能值会产生几种可能的格式字符串(有关使用的说明符,请参见 DATE_FORMAT() 函数描述中的表格)。ISO 格式是指 ISO 9075,而不是 ISO 8601。The possible values for the first and second arguments result in several possible format strings (for the specifiers used, see the table in the DATE_FORMAT() function description). ISO format refers to ISO 9075, not ISO 8601.

    函数调用Function Call 结果Result
    GET_FORMAT(DATE,'USA') '%m.%d.%Y'
    GET_FORMAT(DATE,'JIS') '%Y-%m-%d'
    GET_FORMAT(DATE,'ISO') '%Y-%m-%d'
    GET_FORMAT(DATE,'EUR') '%d.%m.%Y'
    GET_FORMAT(DATE,'INTERNAL') '%Y%m%d'
    GET_FORMAT(DATETIME,'USA') '%Y-%m-%d %H.%i.%s'
    GET_FORMAT(DATETIME,'JIS') '%Y-%m-%d %H:%i:%s'
    GET_FORMAT(DATETIME,'ISO') '%Y-%m-%d %H:%i:%s'
    GET_FORMAT(DATETIME,'EUR') '%Y-%m-%d %H.%i.%s'
    GET_FORMAT(DATETIME,'INTERNAL') '%Y%m%d%H%i%s'
    GET_FORMAT(TIME,'USA') '%h:%i:%s %p'
    GET_FORMAT(TIME,'JIS') '%H:%i:%s'
    GET_FORMAT(TIME,'ISO') '%H:%i:%s'
    GET_FORMAT(TIME,'EUR') '%H.%i.%s'
    GET_FORMAT(TIME,'INTERNAL') '%H%i%s'

    TIMESTAMP 也可以用作 GET_FORMAT() 的第一个参数,在这种情况下,函数返回的值与 DATETIME 相同。TIMESTAMP can also be used as the first argument to GET_FORMAT(), in which case the function returns the same values as for DATETIME.

    mysql> SELECT DATE_FORMAT('2003-10-03',GET_FORMAT(DATE,'EUR'));
            -> '03.10.2003'
    mysql> SELECT STR_TO_DATE('10.31.2003',GET_FORMAT(DATE,'USA'));
            -> '2003-10-31'
    
  • HOUR(time)

    返回time的小时。返回值的范围对于一天中的时间值为0到23。然而,TIME值的范围实际上更大,因此HOUR可以返回大于23的值。如果time为NULL,则返回NULL。Returns the hour for time. The range of the return value is 0 to 23 for time-of-day values. However, the range of TIME values actually is much larger, so HOUR can return values greater than 23. Returns NULL if time is NULL.

    mysql> SELECT HOUR('10:05:03');
            -> 10
    mysql> SELECT HOUR('272:59:59');
            -> 272
    
  • LAST_DAY(date)

    获取日期或日期时间值,并返回对应月份的最后一天的值。如果参数无效或为NULL,则返回NULL。Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid or NULL.

    mysql> SELECT LAST_DAY('2003-02-05');
            -> '2003-02-28'
    mysql> SELECT LAST_DAY('2004-02-05');
            -> '2004-02-29'
    mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
            -> '2004-01-31'
    mysql> SELECT LAST_DAY('2003-03-32');
            -> NULL
    
  • LOCALTIME, LOCALTIME([fsp])

    LOCALTIME 和 LOCALTIME() 是 NOW() 的同义词。LOCALTIME and LOCALTIME() are synonyms for NOW().

  • LOCALTIMESTAMP, LOCALTIMESTAMP([fsp])

    LOCALTIMESTAMP 和 LOCALTIMESTAMP() 是 NOW() 的同义词。LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW().

  • MAKEDATE(year,dayofyear)

    根据年份和年日值返回一个日期。dayofyear 必须大于 0,否则结果为 NULL。如果任一参数为 NULL,结果也为 NULL。Returns a date, given year and day-of-year values. dayofyear must be greater than 0 or the result is NULL. The result is also NULL if either argument is NULL.

    mysql> SELECT MAKEDATE(2011,31), MAKEDATE(2011,32);
            -> '2011-01-31', '2011-02-01'
    mysql> SELECT MAKEDATE(2011,365), MAKEDATE(2014,365);
            -> '2011-12-31', '2014-12-31'
    mysql> SELECT MAKEDATE(2011,0);
            -> NULL
    
  • MAKETIME(hour,minute,second)

    返回从 hour、minute 和 second 参数计算得出的时间值。如果任何参数为 NULL,则返回 NULL。Returns a time value calculated from the hour, minute, and second arguments. Returns NULL if any of its arguments are NULL.

    second 参数可以包含小数部分。The second argument can have a fractional part.

    mysql> SELECT MAKETIME(12,15,30);
            -> '12:15:30'
    
  • MICROSECOND(expr)

    Returns the microseconds from the time or datetime expression expr as a number in the range from 0到999999. Returns NULL返回expr is NULL.Returns the microseconds from the time or datetime expression expr as a number in the range from 0 to 999999. Returns NULL if expr is NULL.

    mysql> SELECT MICROSECOND('12:00:00.123456');
            -> 123456
    mysql> SELECT MICROSECOND('2019-12-31 23:59:59.000010');
            -> 10
    
  • MINUTE(time)MINUTE(time)

    Returns the minute for time, in the range 0到59,或NULL返回time is NULL.Returns the minute for time, in the range 0 to 59, or NULL if time is NULL.

    mysql> SELECT MINUTE('2008-02-03 10:05:03');
            -> 5
    
  • MONTH(date)MONTH(date)

    返回 date 的月份,范围为 1 到 12,对应一月至十二月,或对于月份为零的日期如 '0000-00-00' 或 '2008-00-00' 返回 0。如果 date 为 NULL,则返回 NULL。Returns the month for date, in the range 1 to 12 for January to December, or 0 for dates such as '0000-00-00' or '2008-00-00' that have a zero month part. Returns NULL if date is NULL.

    mysql> SELECT MONTH('2008-02-03');
            -> 2
    
  • MONTHNAME(date)MONTHNAME(date)

    返回date的月份全名。月份名称使用的语言由系统变量lc_time_names的值控制(第 12.16 节,“MySQL 服务器本地化支持”)。如果date是NULL,则返回NULL。Returns the full name of the month for date. The language used for the name is controlled by the value of the lc_time_names system variable (Section 12.16, “MySQL Server Locale Support”). Returns NULL if date is NULL.

    mysql> SELECT MONTHNAME('2008-02-03');
            -> 'February'
    
  • NOW([fsp])

    返回当前日期和时间,格式为 'YYYY-MM-DD hh:mm:ss' 或 YYYYMMDDhhmmss,具体取决于函数是在字符串还是数字环境中使用。该值以会话时区表示。Returns the current date and time as a value in 'YYYY-MM-DD hh:mm:ss' or YYYYMMDDhhmmss format, depending on whether the function is used in string or numeric context. The value is expressed in the session time zone.

    如果提供了fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If the fsp argument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.

    mysql> SELECT NOW();
            -> '2007-12-15 23:50:26'
    mysql> SELECT NOW() + 0;
            -> 20071215235026.000000
    

    NOW() 返回一个恒定的时间,表示语句开始执行时的时间。(在存储函数或触发器中,NOW() 返回函数或触发语句开始执行时的时间。)这与 SYSDATE() 的行为不同,后者返回其执行时的确切时间。NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes.

    mysql> SELECT NOW(), SLEEP(2), NOW();
    +---------------------+----------+---------------------+
    | NOW()               | SLEEP(2) | NOW()               |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
    +---------------------+----------+---------------------+
    
    mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
    +---------------------+----------+---------------------+
    | SYSDATE()           | SLEEP(2) | SYSDATE()           |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
    +---------------------+----------+---------------------+
    

    此外,SET TIMESTAMP 语句会影响 NOW() 返回的值,但不会影响 SYSDATE()。这意味着二进制日志中的时间戳设置不会影响对 SYSDATE() 的调用。将时间戳设置为非零值会导致每次后续调用 NOW() 时都返回该值。将时间戳设置为零会取消此效果,使 NOW() 再次返回当前日期和时间。In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE(). Setting the timestamp to a nonzero value causes each subsequent invocation of NOW() to return that value. Setting the timestamp to zero cancels this effect so that NOW() once again returns the current date and time.

    有关两个函数之间差异的更多信息,请参阅 SYSDATE() 的描述。See the description for SYSDATE() for additional information about the differences between the two functions.

  • PERIOD_ADD(P,N)

    在周期 P(格式为 YYMM 或 YYYYMM)中加上 N 个月。返回值格式为 YYYYMM。Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM.

    Note

    周期参数 P 不是 日期值。The period argument P is not a date value.

    如果P或N为NULL,此函数将返回NULL。This function returns NULL if P or N is NULL.

    mysql> SELECT PERIOD_ADD(200801,2);
            -> 200803
    
  • PERIOD_DIFF(P1,P2)

    Returns the number of months between periods P1以及P2. P1以及P2 should be in the format YYMM或者YYYYMM. Note that the period arguments P1以及P2 are 在多线程系统中 date values.Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values.

    如果P1或P2是NULL,此函数将返回NULL。This function returns NULL if P1 or P2 is NULL.

    mysql> SELECT PERIOD_DIFF(200802,200703);
            -> 11
    
  • QUARTER(date)

    返回date所属年份的季度,范围从1到4,如果date是NULL,则返回NULL。Returns the quarter of the year for date, in the range 1 to 4, or NULL if date is NULL.

    mysql> SELECT QUARTER('2008-04-01');
            -> 2
    
  • SECOND(time)

    返回 time 的秒数,范围为 0 到 59,如果 time 为 NULL 则返回 NULL。Returns the second for time, in the range 0 to 59, or NULL if time is NULL.

    mysql> SELECT SECOND('10:05:03');
            -> 3
    
  • SEC_TO_TIME(seconds)

    返回将 seconds 参数转换为小时、分钟和秒的 TIME 值。结果的范围受 TIME 数据类型的限制。如果参数对应的值超出该范围,则会产生警告。Returns the seconds argument, converted to hours, minutes, and seconds, as a TIME value. The range of the result is constrained to that of the TIME data type. A warning occurs if the argument corresponds to a value outside that range.

    如果seconds是NULL,该函数将返回NULL。The function returns NULL if seconds is NULL.

    mysql> SELECT SEC_TO_TIME(2378);
            -> '00:39:38'
    mysql> SELECT SEC_TO_TIME(2378) + 0;
            -> 3938
    
  • STR_TO_DATE(str,format)

    这是DATE_FORMAT()函数的逆函数。它接收一个字符串str和一个格式字符串format。STR_TO_DATE()会返回一个DATETIME值,如果格式字符串同时包含日期和时间部分;如果字符串只包含日期或时间部分,则返回DATE或TIME值。如果str或format为NULL,则函数返回NULL。如果从str中提取的日期、时间或日期时间值无法按照服务器遵循的规则解析,STR_TO_DATE()将返回NULL并产生警告。This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts. If str or format is NULL, the function returns NULL. If the date, time, or datetime value extracted from str cannot be parsed according to the rules followed by the server, STR_TO_DATE() returns NULL and produces a warning.

    服务器扫描 str,尝试将 format 与之匹配。格式字符串可以包含文字字符和以 % 开头的格式说明符。format 中的文字字符必须在 str 中逐字匹配。format 中的格式说明符必须匹配 str 中的日期或时间部分。有关可以在 format 中使用的说明符,请参阅 DATE_FORMAT() 函数说明。The server scans str attempting to match format to it. The format string can contain literal characters and format specifiers beginning with %. Literal characters in format must match literally in str. Format specifiers in format must match a date or time part in str. For the specifiers that can be used in format, see the DATE_FORMAT() function description.

    mysql> SELECT STR_TO_DATE('01,5,2013','%d,%m,%Y');
            -> '2013-05-01'
    mysql> SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y');
            -> '2013-05-01'
    

    扫描从 str 的开头开始,如果发现 format 不匹配则扫描失败。str 末尾的额外字符将被忽略。Scanning starts at the beginning of str and fails if format is found not to match. Extra characters at the end of str are ignored.

    mysql> SELECT STR_TO_DATE('a09:30:17','a%h:%i:%s');
            -> '09:30:17'
    mysql> SELECT STR_TO_DATE('a09:30:17','%h:%i:%s');
            -> NULL
    mysql> SELECT STR_TO_DATE('09:30:17a','%h:%i:%s');
            -> '09:30:17'
    

    未指定的日期或时间部分的值为 0,因此 str 中不完整指定的值会产生部分或全部设置为 0 的结果:Unspecified date or time parts have a value of 0, so incompletely specified values in str produce a result with some or all parts set to 0:

    mysql> SELECT STR_TO_DATE('abc','abc');
            -> '0000-00-00'
    mysql> SELECT STR_TO_DATE('9','%m');
            -> '0000-09-00'
    mysql> SELECT STR_TO_DATE('9','%s');
            -> '00:00:09'
    

    日期值的各部分范围检查如第 13.2.2 节,“DATE、DATETIME 和 TIMESTAMP 类型”中所述。 这意味着,例如,“零”允许日期或部分值为 0 的日期,除非 SQL 模式被设置为不允许此类值。Range checking on the parts of date values is as described in Section 13.2.2, “The DATE, DATETIME, and TIMESTAMP Types”. This means, for example, that “zero” dates or dates with part values of 0 are permitted unless the SQL mode is set to disallow such values.

    mysql> SELECT STR_TO_DATE('00/00/0000', '%m/%d/%Y');
            -> '0000-00-00'
    mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
            -> '2004-04-31'
    

    如果启用了 NO_ZERO_DATE SQL 模式,则不允许使用零日期。在这种情况下,STR_TO_DATE() 会返回 NULL 并生成警告:If the NO_ZERO_DATE SQL mode is enabled, zero dates are disallowed. In that case, STR_TO_DATE() returns NULL and generates a warning:

    mysql> SET sql_mode = '';
    mysql> SELECT STR_TO_DATE('00/00/0000', '%m/%d/%Y');
    +---------------------------------------+
    | STR_TO_DATE('00/00/0000', '%m/%d/%Y') |
    +---------------------------------------+
    | 0000-00-00                            |
    +---------------------------------------+
    mysql> SET sql_mode = 'NO_ZERO_DATE';
    mysql> SELECT STR_TO_DATE('00/00/0000', '%m/%d/%Y');
    +---------------------------------------+
    | STR_TO_DATE('00/00/0000', '%m/%d/%Y') |
    +---------------------------------------+
    | NULL                                  |
    +---------------------------------------+
    mysql> SHOW WARNINGS\G
    *************************** 1. row ***************************
      Level: Warning
       Code: 1411
    Message: Incorrect datetime value: '00/00/0000' for function str_to_date
    

    在某些早期版本的 MySQL 中,可以向该函数传递无效的日期字符串,例如 '2021-11-31'。在 MySQL 8.4 中,STR_TO_DATE() 会执行完整的范围检查,如果转换后的日期无效,则会引发错误。In some previous versions of MySQL, it was possible to pass an invalid date string such as '2021-11-31' to this function. In MySQL 8.4, STR_TO_DATE() performs complete range checking and raises an error if the date after conversion would be invalid.

    Note

    您不能使用格式 "%X%V" 将年份-周字符串转换为日期,因为如果某周跨越了月份边界,年份和周的组合并不能唯一确定年份和月份。要将年份-周转换为日期,您还需要指定星期几:You cannot use format "%X%V" to convert a year-week string to a date because the combination of a year and week does not uniquely identify a year and month if the week crosses a month boundary. To convert a year-week to a date, you should also specify the weekday:

    mysql> SELECT STR_TO_DATE('200442 Monday', '%X%V %W');
            -> '2004-10-18'
    

    您还应该注意,对于日期和日期时间值的日期部分,STR_TO_DATE() 仅检查单独的年、月和日的有效性。更准确地说,这意味着年份会被检查,以确保其在 0-9999 的范围内,月份会被检查,以确保其在 1-12 的范围内,日会被检查,以确保其在 1-31 的范围内,但服务器不会检查这些值的组合。例如,SELECT STR_TO_DATE('23-2-31', '%Y-%m-%d') 返回 2023-02-31。启用或禁用 ALLOW_INVALID_DATES 服务器 SQL 模式对此行为没有影响。有关更多信息,请参见 第 13.2.2 节,“DATE、DATETIME 和 TIMESTAMP 类型”。You should also be aware that, for dates and the date portions of datetime values, STR_TO_DATE() checks (only) the individual year, month, and day of month values for validity. More precisely, this means that the year is checked to be sure that it is in the range 0-9999 inclusive, the month is checked to ensure that it is in the range 1-12 inclusive, and the day of month is checked to make sure that it is in the range 1-31 inclusive, but the server does not check the values in combination. For example, SELECT STR_TO_DATE('23-2-31', '%Y-%m-%d') returns 2023-02-31. Enabling or disabling the ALLOW_INVALID_DATES server SQL mode has no effect on this behavior. See Section 13.2.2, “The DATE, DATETIME, and TIMESTAMP Types”, for more information.

  • SUBDATE(date,INTERVAL expr unit), SUBDATE(expr,days)

    当以第二个参数的 INTERVAL 形式调用时,SUBDATE() 是 DATE_SUB() 的同义词。有关 INTERVAL unit 参数的信息,请参阅 DATE_ADD() 的讨论。When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD().

    mysql> SELECT DATE_SUB('2008-01-02', INTERVAL 31 DAY);
            -> '2007-12-02'
    mysql> SELECT SUBDATE('2008-01-02', INTERVAL 31 DAY);
            -> '2007-12-02'
    

    第二种形式允许使用整数值作为 days。在这种情况下,它被解释为应从日期或日期时间表达式 expr 中减去的天数。The second form enables the use of an integer value for days. In such cases, it is interpreted as the number of days to be subtracted from the date or datetime expression expr.

    mysql> SELECT SUBDATE('2008-01-02 12:00:00', 31);
            -> '2007-12-02 12:00:00'
    

    如果其任何参数为 NULL,此函数将返回 NULL。This function returns NULL if any of its arguments are NULL.

  • SUBTIME(expr1,expr2)

    SUBTIME() 返回以与 expr1 相同格式表示的 expr1 − expr2 的值。expr1 是时间或日期时间表达式,而 expr2 是时间表达式。SUBTIME() returns expr1 − expr2 expressed as a value in the same format as expr1. expr1 is a time or datetime expression, and expr2 is a time expression.

    此函数返回类型的解析方式与ADDTIME()函数的解析方式相同;有关更多信息,请参阅该函数的说明。Resolution of this function's return type is performed as it is for the ADDTIME() function; see the description of that function for more information.

    mysql> SELECT SUBTIME('2007-12-31 23:59:59.999999','1 1:1:1.000002');
            -> '2007-12-30 22:58:58.999997'
    mysql> SELECT SUBTIME('01:00:00.999999', '02:00:00.999998');
            -> '-00:59:59.999999'
    

    如果 expr1 或 expr2 为 NULL,则该函数返回 NULL。This function returns NULL if expr1 or expr2 is NULL.

  • SYSDATE([fsp])

    返回当前日期和时间,格式为'YYYY-MM-DD hh:mm:ss'或YYYYMMDDhhmmss,取决于该函数是在字符串还是数字上下文中使用。Returns the current date and time as a value in 'YYYY-MM-DD hh:mm:ss' or YYYYMMDDhhmmss format, depending on whether the function is used in string or numeric context.

    如果提供了fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If the fsp argument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.

    SYSDATE() 返回其执行时的时间。这与 NOW() 的行为不同,后者返回一个常量时间,表示语句开始执行的时间。(在存储函数或触发器中,NOW() 返回函数或触发语句开始执行的时间。)SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.)

    mysql> SELECT NOW(), SLEEP(2), NOW();
    +---------------------+----------+---------------------+
    | NOW()               | SLEEP(2) | NOW()               |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
    +---------------------+----------+---------------------+
    
    mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
    +---------------------+----------+---------------------+
    | SYSDATE()           | SLEEP(2) | SYSDATE()           |
    +---------------------+----------+---------------------+
    | 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
    +---------------------+----------+---------------------+
    

    此外,SET TIMESTAMP 语句会影响 NOW() 返回的值,但不会影响 SYSDATE()。这意味着二进制日志中的时间戳设置不会影响对 SYSDATE() 的调用。In addition, the SET TIMESTAMP statement affects the value returned by NOW() but not by SYSDATE(). This means that timestamp settings in the binary log have no effect on invocations of SYSDATE().

    因为 SYSDATE() 即使在同一条语句中也可能返回不同的值,并且不受 SET TIMESTAMP 影响,所以它是非确定性的,因此如果使用基于语句的二进制日志,它在复制中是不安全的。如果这是一个问题,你可以使用基于行的日志。Because SYSDATE() can return different values even within the same statement, and is not affected by SET TIMESTAMP, it is nondeterministic and therefore unsafe for replication if statement-based binary logging is used. If that is a problem, you can use row-based logging.

    或者,您可以使用 --sysdate-is-now 选项,使 SYSDATE() 成为 NOW() 的别名。如果该选项在复制源服务器和副本服务器上都使用,则此方法有效。Alternatively, you can use the --sysdate-is-now option to cause SYSDATE() to be an alias for NOW(). This works if the option is used on both the replication source server and the replica.

    SYSDATE() 的非确定性特性也意味着在计算引用它的表达式时无法使用索引。The nondeterministic nature of SYSDATE() also means that indexes cannot be used for evaluating expressions that refer to it.

  • TIME(expr)

    提取时间或日期时间表达式 expr 的时间部分,并将其作为字符串返回。如果 expr 为 NULL,则返回 NULL。Extracts the time part of the time or datetime expression expr and returns it as a string. Returns NULL if expr is NULL.

    该函数在基于语句的复制中不安全。如果在 binlog_format 设置为 STATEMENT 时使用此函数,将记录一个警告。This function is unsafe for statement-based replication. A warning is logged if you use this function when binlog_format is set to STATEMENT.

    mysql> SELECT TIME('2003-12-31 01:02:03');
            -> '01:02:03'
    mysql> SELECT TIME('2003-12-31 01:02:03.000123');
            -> '01:02:03.000123'
    
  • TIMEDIFF(expr1,expr2)

    TIMEDIFF() 返回 expr1 − expr2 的时间值。expr1 和 expr2 是字符串,会被转换为 TIME 或 DATETIME 表达式;转换后必须属于同一类型。如果 expr1 或 expr2 为 NULL,则返回 NULL。TIMEDIFF() returns expr1 − expr2 expressed as a time value. expr1 and expr2 are strings which are converted to TIME or DATETIME expressions; these must be of the same type following conversion. Returns NULL if expr1 or expr2 is NULL.

    TIMEDIFF() 返回的结果限制在 TIME 值允许的范围内。或者,你可以使用 TIMESTAMPDIFF() 和 UNIX_TIMESTAMP() 中的任意一个函数,它们都返回整数。The result returned by TIMEDIFF() is limited to the range allowed for TIME values. Alternatively, you can use either of the functions TIMESTAMPDIFF() and UNIX_TIMESTAMP(), both of which return integers.

    mysql> SELECT TIMEDIFF('2000-01-01 00:00:00',
        ->                 '2000-01-01 00:00:00.000001');
            -> '-00:00:00.000001'
    mysql> SELECT TIMEDIFF('2008-12-31 23:59:59.000001',
        ->                 '2008-12-30 01:01:01.000002');
            -> '46:58:57.999999'
    
  • TIMESTAMP(expr), TIMESTAMP(expr1,expr2)

    当只有一个参数时,此函数返回日期或日期时间表达式expr作为日期时间值。若有两个参数,它会将时间表达式expr2加到日期或日期时间表达式expr1上,并返回结果作为日期时间值。如果expr、expr1或expr2为NULL,则返回NULL。With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value. Returns NULL if expr, expr1, or expr2 is NULL.

    mysql> SELECT TIMESTAMP('2003-12-31');
            -> '2003-12-31 00:00:00'
    mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');
            -> '2004-01-01 00:00:00'
    
  • TIMESTAMPADD(unit,interval,datetime_expr)TIMESTAMPADD(unit,interval,datetime_expr)

    将整数表达式interval添加到日期或日期时间表达式datetime_expr中。interval的单位由unit参数指定,该参数应为以下值之一:MICROSECOND(微秒)、SECOND、MINUTE、HOUR、DAY、WEEK、MONTH、QUARTER或YEAR。Adds the integer expression interval to the date or datetime expression datetime_expr. The unit for interval is given by the unit argument, which should be one of the following values: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

    可以使用所示的关键字之一指定unit值,或者使用SQL_TSI_前缀。例如,DAY和SQL_TSI_DAY都是合法的。The unit value may be specified using one of keywords as shown, or with a prefix of SQL_TSI_. For example, DAY and SQL_TSI_DAY both are legal.

    如果interval或datetime_expr为NULL,则此函数返回NULL。This function returns NULL if interval or datetime_expr is NULL.

    mysql> SELECT TIMESTAMPADD(MINUTE, 1, '2003-01-02');
            -> '2003-01-02 00:01:00'
    mysql> SELECT TIMESTAMPADD(WEEK,1,'2003-01-02');
            -> '2003-01-09'
    

    当向 DATE 或 DATETIME 值添加 MONTH 间隔时,如果得到的日期包含该月不存在的日期,则该日会调整为该月的最后一天,如下所示:When adding a MONTH interval to a DATE or DATETIME value, and the resulting date includes a day that does not exist in the given month, the day is adjusted to the last day of the month, as shown here:

    mysql> SELECT TIMESTAMPADD(MONTH, 1, DATE '2024-03-30') AS t1, 
         >        TIMESTAMPADD(MONTH, 1, DATE '2024-03-31') AS t2;
    +------------+------------+
    | t1         | t2         |
    +------------+------------+
    | 2024-04-30 | 2024-04-30 |
    +------------+------------+
    1 row in set (0.00 sec)
    
  • TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)

    返回 datetime_expr2 − datetime_expr1,其中 datetime_expr1 和 datetime_expr2 是日期或日期时间表达式。一个表达式可以是日期,另一个可以是日期时间;必要时,日期值将被视为时间部分为 '00:00:00' 的日期时间。结果(一个整数)的单位由 unit 参数给出。unit 的合法值与 TIMESTAMPADD() 函数描述中列出的值相同。Returns datetime_expr2 − datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument. The legal values for unit are the same as those listed in the description of the TIMESTAMPADD() function.

    如果 datetime_expr1 或 datetime_expr2 为 NULL,此函数将返回 NULL。This function returns NULL if datetime_expr1 or datetime_expr2 is NULL.

    mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
            -> 3
    mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
            -> -1
    mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
            -> 128885
    
    Note

    此函数的日期或日期时间参数顺序与使用 2 个参数调用 TIMESTAMP() 函数时的顺序相反。The order of the date or datetime arguments for this function is the opposite of that used with the TIMESTAMP() function when invoked with 2 arguments.

  • TIME_FORMAT(time,format)TIME_FORMAT(time,format)

    这个用法类似于DATE_FORMAT()函数,但format字符串可以只包含小时、分钟、秒和微秒的格式说明符。其他说明符会返回NULL或0。如果time或format为NULL,TIME_FORMAT()将返回NULL。This is used like the DATE_FORMAT() function, but the format string may contain format specifiers only for hours, minutes, seconds, and microseconds. Other specifiers produce a NULL or 0. TIME_FORMAT() returns NULL if time or format is NULL.

    如果 time 值包含的小时部分大于 23,则 %H 和 %k 小时格式说明符会生成大于通常 0..23 范围的值。其他小时格式说明符会生成小时值对 12 取模的结果。If the time value contains an hour part that is greater than 23, the %H and %k hour format specifiers produce a value larger than the usual range of 0..23. The other hour format specifiers produce the hour value modulo 12.

    mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');
            -> '100 100 04 04 4'
    
  • TIME_TO_SEC(time)TIME_TO_SEC(time)

    返回将 time 参数转换为秒的值。如果 time 为 NULL,则返回 NULL。Returns the time argument, converted to seconds. Returns NULL if time is NULL.

    mysql> SELECT TIME_TO_SEC('22:23:00');
            -> 80580
    mysql> SELECT TIME_TO_SEC('00:39:38');
            -> 2378
    
  • TO_DAYS(date)TO_DAYS(date)

    给定一个日期date,返回日数编号(自公元 0 年以来的天数)。如果date为NULL,则返回NULL。Given a date date, returns a day number (the number of days since year 0). Returns NULL if date is NULL.

    mysql> SELECT TO_DAYS(950501);
            -> 728779
    mysql> SELECT TO_DAYS('2007-10-07');
            -> 733321
    

    TO_DAYS() 不适用于公历(1582 年)出现之前的日期值,因为它没有考虑日历更改时丢失的天数。对于 1582 年之前的日期(以及其他地区可能更晚的年份),此函数的结果不可靠。详情请参阅 第 13.2.7 节,“MySQL 使用的日历是什么?”。TO_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582), because it does not take into account the days that were lost when the calendar was changed. For dates before 1582 (and possibly a later year in other locales), results from this function are not reliable. See Section 13.2.7, “What Calendar Is Used By MySQL?”, for details.

    请记住,MySQL 使用第 13.2 节,“日期和时间数据类型”中的规则将日期中的两位数年份转换为四位数。例如,'2008-10-07' 和 '08-10-07' 被视为相同的日期:Remember that MySQL converts two-digit year values in dates to four-digit form using the rules in Section 13.2, “Date and Time Data Types”. For example, '2008-10-07' and '08-10-07' are seen as identical dates:

    mysql> SELECT TO_DAYS('2008-10-07'), TO_DAYS('08-10-07');
            -> 733687, 733687
    

    在 MySQL 中,零日期被定义为 '0000-00-00',即使这个日期本身被认为是无效的。这意味着,对于 '0000-00-00' 和 '0000-01-01',TO_DAYS() 返回如下所示的值:In MySQL, the zero date is defined as '0000-00-00', even though this date is itself considered invalid. This means that, for '0000-00-00' and '0000-01-01', TO_DAYS() returns the values shown here:

    mysql> SELECT TO_DAYS('0000-00-00');
    +-----------------------+
    | to_days('0000-00-00') |
    +-----------------------+
    |                  NULL |
    +-----------------------+
    1 row in set, 1 warning (0.00 sec)
    
    mysql> SHOW WARNINGS;
    +---------+------+----------------------------------------+
    | Level   | Code | Message                                |
    +---------+------+----------------------------------------+
    | Warning | 1292 | Incorrect datetime value: '0000-00-00' |
    +---------+------+----------------------------------------+
    1 row in set (0.00 sec)
    
    
    mysql> SELECT TO_DAYS('0000-01-01');
    +-----------------------+
    | to_days('0000-01-01') |
    +-----------------------+
    |                     1 |
    +-----------------------+
    1 row in set (0.00 sec)
    

    无论是否启用了 ALLOW_INVALID_DATES SQL 服务器模式,这都是正确的。This is true whether or not the ALLOW_INVALID_DATES SQL server mode is enabled.

  • TO_SECONDS(expr)TO_SECONDS(expr)

    给定一个日期或日期时间 expr,返回从公元 0 年起的秒数。如果 expr 不是有效的日期或日期时间值(包括 NULL),则返回 NULL。Given a date or datetime expr, returns the number of seconds since the year 0. If expr is not a valid date or datetime value (including NULL), it returns NULL.

    mysql> SELECT TO_SECONDS(950501);
            -> 62966505600
    mysql> SELECT TO_SECONDS('2009-11-29');
            -> 63426672000
    mysql> SELECT TO_SECONDS('2009-11-29 13:43:32');
            -> 63426721412
    mysql> SELECT TO_SECONDS( NOW() );
            -> 63426721458
    

    像 TO_DAYS() 一样,TO_SECONDS() 并不适用于公元格里历(1582 年)之前的日期,因为它没有考虑到日历更改时丢失的天数。对于 1582 年之前的日期(以及其他地区可能的更晚年份),此函数的结果不可靠。详情请参见 第 13.2.7 节,“MySQL 使用的日历”。Like TO_DAYS(), TO_SECONDS() is not intended for use with values that precede the advent of the Gregorian calendar (1582), because it does not take into account the days that were lost when the calendar was changed. For dates before 1582 (and possibly a later year in other locales), results from this function are not reliable. See Section 13.2.7, “What Calendar Is Used By MySQL?”, for details.

    像 TO_DAYS() 一样,TO_SECONDS() 使用 第 13.2 节,“日期和时间数据类型” 中的规则,将日期中的两位数年份转换为四位数形式。Like TO_DAYS(), TO_SECONDS(), converts two-digit year values in dates to four-digit form using the rules in Section 13.2, “Date and Time Data Types”.

    在 MySQL 中,零日期定义为 '0000-00-00',尽管这个日期本身被认为是无效的。这意味着,对于 '0000-00-00' 和 '0000-01-01',TO_SECONDS() 返回此处显示的值:In MySQL, the zero date is defined as '0000-00-00', even though this date is itself considered invalid. This means that, for '0000-00-00' and '0000-01-01', TO_SECONDS() returns the values shown here:

    mysql> SELECT TO_SECONDS('0000-00-00');
    +--------------------------+
    | TO_SECONDS('0000-00-00') |
    +--------------------------+
    |                     NULL |
    +--------------------------+
    1 row in set, 1 warning (0.00 sec)
    
    mysql> SHOW WARNINGS;
    +---------+------+----------------------------------------+
    | Level   | Code | Message                                |
    +---------+------+----------------------------------------+
    | Warning | 1292 | Incorrect datetime value: '0000-00-00' |
    +---------+------+----------------------------------------+
    1 row in set (0.00 sec)
    
    
    mysql> SELECT TO_SECONDS('0000-01-01');
    +--------------------------+
    | TO_SECONDS('0000-01-01') |
    +--------------------------+
    |                    86400 |
    +--------------------------+
    1 row in set (0.00 sec)
    

    无论是否启用了 ALLOW_INVALID_DATES SQL 服务器模式,这都是正确的。This is true whether or not the ALLOW_INVALID_DATES SQL server mode is enabled.

  • UNIX_TIMESTAMP([date])UNIX_TIMESTAMP([date])

    如果调用 UNIX_TIMESTAMP() 时没有提供 date 参数,它将返回一个 Unix 时间戳,表示自 '1970-01-01 00:00:00' UTC 起的秒数。If UNIX_TIMESTAMP() is called with no date argument, it returns a Unix timestamp representing seconds since '1970-01-01 00:00:00' UTC.

    如果调用 UNIX_TIMESTAMP() 并传入 date 参数,它将返回该参数自 '1970-01-01 00:00:00' UTC 起的秒数。服务器将 date 解释为会话时区的值,并将其转换为 UTC 的内部 Unix 时间戳值。(客户端可以按照 第 7.1.15 节“ MySQL 服务器时区支持” 中的说明设置会话时区。)date 参数可以是 DATE、DATETIME 或 TIMESTAMP 字符串,或者是 YYMMDD、YYMMDDhhmmss、YYYYMMDD 或 YYYYMMDDhhmmss 格式的数字。如果参数包含时间部分,它可以选择性地包含秒的小数部分。If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. The server interprets date as a value in the session time zone and converts it to an internal Unix timestamp value in UTC. (Clients can set the session time zone as described in Section 7.1.15, “MySQL Server Time Zone Support”.) The date argument may be a DATE, DATETIME, or TIMESTAMP string, or a number in YYMMDD, YYMMDDhhmmss, YYYYMMDD, or YYYYMMDDhhmmss format. If the argument includes a time part, it may optionally include a fractional seconds part.

    如果没有给出参数,或者参数不包含秒的小数部分,返回值为整数;如果给出的参数包含秒的小数部分,则返回值为 DECIMAL。The return value is an integer if no argument is given or the argument does not include a fractional seconds part, or DECIMAL if an argument is given that includes a fractional seconds part.

    当 date 参数是 TIMESTAMP 列时,UNIX_TIMESTAMP() 直接返回内部时间戳值,不进行隐式的 “字符串转 Unix 时间戳” 转换。When the date argument is a TIMESTAMP column, UNIX_TIMESTAMP() returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.

    参数值的有效范围与TIMESTAMP数据类型相同:对于 32 位平台,UTC 时间从'1970-01-01 00:00:01.000000'到'2038-01-19 03:14:07.999999';对于在 64 位平台上运行的 MySQL,UNIX_TIMESTAMP()的参数值有效范围为 UTC 时间从'1970-01-01 00:00:01.000000'到'3001-01-19 03:14:07.999999'(对应 32536771199.999999 秒)。The valid range of argument values is the same as for the TIMESTAMP data type: '1970-01-01 00:00:01.000000' UTC to '2038-01-19 03:14:07.999999' UTC for 32-bit platforms; for MySQL running on 64-bit platforms, the valid range of argument values for UNIX_TIMESTAMP() is '1970-01-01 00:00:01.000000' UTC to '3001-01-19 03:14:07.999999' UTC (corresponding to 32536771199.999999 seconds).

    无论 MySQL 版本或平台架构如何,如果你向 UNIX_TIMESTAMP() 传递一个超出范围的日期,它将返回 0。如果 date 为 NULL,它将返回 NULL。Regardless of MySQL version or platform architecture, if you pass an out-of-range date to UNIX_TIMESTAMP(), it returns 0. If date is NULL, it returns NULL.

    mysql> SELECT UNIX_TIMESTAMP();
            -> 1447431666
    mysql> SELECT UNIX_TIMESTAMP('2015-11-13 10:20:19');
            -> 1447431619
    mysql> SELECT UNIX_TIMESTAMP('2015-11-13 10:20:19.012');
            -> 1447431619.012
    

    如果您使用 UNIX_TIMESTAMP() 和 FROM_UNIXTIME() 在非 UTC 时区值与 Unix 时间戳值之间进行转换,该转换是有损的,因为映射在两个方向上并非一一对应。例如,由于本地时区更改(如夏令时 DST)的惯例,UNIX_TIMESTAMP() 可能会将在非 UTC 时区中不同的两个值映射到相同的 Unix 时间戳值。FROM_UNIXTIME() 将该值映射回原始值中的其中一个。下面是一个示例,使用在 MET 时区不同的值:If you use UNIX_TIMESTAMP() and FROM_UNIXTIME() to convert between values in a non-UTC time zone and Unix timestamp values, the conversion is lossy because the mapping is not one-to-one in both directions. For example, due to conventions for local time zone changes such as Daylight Saving Time (DST), it is possible for UNIX_TIMESTAMP() to map two values that are distinct in a non-UTC time zone to the same Unix timestamp value. FROM_UNIXTIME() maps that value back to only one of the original values. Here is an example, using values that are distinct in the MET time zone:

    mysql> SET time_zone = 'MET';
    mysql> SELECT UNIX_TIMESTAMP('2005-03-27 03:00:00');
    +---------------------------------------+
    | UNIX_TIMESTAMP('2005-03-27 03:00:00') |
    +---------------------------------------+
    |                            1111885200 |
    +---------------------------------------+
    mysql> SELECT UNIX_TIMESTAMP('2005-03-27 02:00:00');
    +---------------------------------------+
    | UNIX_TIMESTAMP('2005-03-27 02:00:00') |
    +---------------------------------------+
    |                            1111885200 |
    +---------------------------------------+
    mysql> SELECT FROM_UNIXTIME(1111885200);
    +---------------------------+
    | FROM_UNIXTIME(1111885200) |
    +---------------------------+
    | 2005-03-27 03:00:00       |
    +---------------------------+
    
    Note

    要使用诸如 'MET' 或 'Europe/Amsterdam' 这样的命名时区,必须正确设置时区表。有关说明,请参见 第 7.1.15 节,“MySQL 服务器时区支持”。To use named time zones such as 'MET' or 'Europe/Amsterdam', the time zone tables must be properly set up. For instructions, see Section 7.1.15, “MySQL Server Time Zone Support”.

    如果你想要对 UNIX_TIMESTAMP() 列进行相减,你可能需要将它们转换为有符号整数。请参阅 第 14.10 节,“转换函数和运算符”。If you want to subtract UNIX_TIMESTAMP() columns, you might want to cast them to signed integers. See Section 14.10, “Cast Functions and Operators”.

  • UTC_DATE, UTC_DATE()

    返回当前 UTC 日期,格式为 'YYYY-MM-DD' 或 YYYYMMDD,取决于该函数是在字符串上下文还是数字上下文中使用。Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in string or numeric context.

    mysql> SELECT UTC_DATE(), UTC_DATE() + 0;
            -> '2003-08-14', 20030814
    
  • UTC_TIME, UTC_TIME([fsp])

    根据函数是在字符串还是数字上下文中使用,返回当前 UTC 时间,格式为 'hh:mm:ss' 或 hhmmss。Returns the current UTC time as a value in 'hh:mm:ss' or hhmmss format, depending on whether the function is used in string or numeric context.

    如果提供了fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If the fsp argument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.

    mysql> SELECT UTC_TIME(), UTC_TIME() + 0;
            -> '18:07:53', 180753.000000
    
  • UTC_TIMESTAMP, UTC_TIMESTAMP([fsp])

    返回当前的 UTC 日期和时间,作为 'YYYY-MM-DD hh:mm:ss' 或 YYYYMMDDhhmmss 格式的值,具体取决于该函数是在字符串上下文还是数字上下文中使用。Returns the current UTC date and time as a value in 'YYYY-MM-DD hh:mm:ss' or YYYYMMDDhhmmss format, depending on whether the function is used in string or numeric context.

    如果提供了fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If the fsp argument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.

    mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0;
            -> '2003-08-14 18:08:04', 20030814180804.000000
    
  • WEEK(date[,mode])WEEK(date[,mode])

    此函数返回date的周数。WEEK()的双参数形式允许您指定周是从星期日还是星期一开始,以及返回值应该是从0到53的范围还是从1到53的范围。如果省略了mode参数,则使用系统变量default_week_format的值。请参阅第 7.1.8 节,“服务器系统变量”。对于NULL日期值,该函数返回NULL。This function returns the week number for date. The two-argument form of WEEK() enables you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used. See Section 7.1.8, “Server System Variables”. For a NULL date value, the function returns NULL.

    下表描述了 mode 参数的工作原理。The following table describes how the mode argument works.

    模式Mode 一周的第一天First day of week 范围Range 第 1 周是第一周 …Week 1 is the first week …
    0 星期日Sunday 0-53 在今年包含一个星期日with a Sunday in this year
    1 星期一Monday 0-53 在今年包含 4 天或更多with 4 or more days this year
    2 星期日Sunday 1-53 在今年包含一个星期日with a Sunday in this year
    3 星期一Monday 1-53 在今年包含 4 天或更多with 4 or more days this year
    4 星期日Sunday 0-53 在今年包含 4 天或更多with 4 or more days this year
    5 星期一Monday 0-53 在今年包含一个星期一with a Monday in this year
    6 星期日Sunday 1-53 在今年包含 4 天或更多with 4 or more days this year
    7 星期一Monday 1-53 在今年包含一个星期一with a Monday in this year

    对于 mode 值意义为 “今年有 4 天或更多时,” 的情况,周数按 ISO 8601:1988 编号:For mode values with a meaning of “with 4 or more days this year,” weeks are numbered according to ISO 8601:1988:

    • 如果包含 1 月 1 日的那一周在新的一年中有 4 天或更多天,它就是第 1 周。If the week containing January 1 has 4 or more days in the new year, it is week 1.

    • 否则,它就是上一年的最后一周,而下一周是第 1 周。Otherwise, it is the last week of the previous year, and the next week is week 1.

    mysql> SELECT WEEK('2008-02-20');
            -> 7
    mysql> SELECT WEEK('2008-02-20',0);
            -> 7
    mysql> SELECT WEEK('2008-02-20',1);
            -> 8
    mysql> SELECT WEEK('2008-12-31',1);
            -> 53
    

    如果一个日期落在上一年的最后一周,如果不使用 2、3、6 或 7 作为可选的 mode 参数,MySQL 将返回 0:If a date falls in the last week of the previous year, MySQL returns 0 if you do not use 2, 3, 6, or 7 as the optional mode argument:

    mysql> SELECT YEAR('2000-01-01'), WEEK('2000-01-01',0);
            -> 2000, 0
    

    有人可能会争辩说,WEEK() 应该返回 52,因为给定的日期实际上发生在 1999 年的第 52 周。然而,WEEK() 返回 0,以便返回值为 “指定年份中的周数。” 这样在与其他从日期中提取日期部分的函数结合使用时,WEEK() 函数是可靠的。One might argue that WEEK() should return 52 because the given date actually occurs in the 52nd week of 1999. WEEK() returns 0 instead so that the return value is “the week number in the given year.” This makes use of the WEEK() function reliable when combined with other functions that extract a date part from a date.

    如果您希望根据包含给定日期所在周第一天的年份来评估结果,请将 0、2、5 或 7 用作可选的 mode 参数。If you prefer a result evaluated with respect to the year that contains the first day of the week for the given date, use 0, 2, 5, or 7 as the optional mode argument.

    mysql> SELECT WEEK('2000-01-01',2);
            -> 52
    

    或者,使用 YEARWEEK() 函数:Alternatively, use the YEARWEEK() function:

    mysql> SELECT YEARWEEK('2000-01-01');
            -> 199952
    mysql> SELECT MID(YEARWEEK('2000-01-01'),5,2);
            -> '52'
    
  • WEEKDAY(date)WEEKDAY(date)

    返回date的星期索引(0 = 星期一,1 = 星期二,… 6 = 星期日)。如果date为NULL,则返回NULL。Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday). Returns NULL if date is NULL.

    mysql> SELECT WEEKDAY('2008-02-03 22:23:00');
            -> 6
    mysql> SELECT WEEKDAY('2007-11-06');
            -> 1
    
  • WEEKOFYEAR(date)WEEKOFYEAR(date)

    返回日期在日历年中的周数,范围从1到53。如果date为NULL,则返回NULL。Returns the calendar week of the date as a number in the range from 1 to 53. Returns NULL if date is NULL.

    WEEKOFYEAR() 是一个兼容性函数,相当于 WEEK(date,3)。WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).

    mysql> SELECT WEEKOFYEAR('2008-02-20');
            -> 8
    
  • YEAR(date)YEAR(date)

    Returns the year for date, in the range 1000到9999,或0 for the “零” date. Returns NULL返回date is NULL.Returns the year for date, in the range 1000 to 9999, or 0 for the “zero” date. Returns NULL if date is NULL.

    mysql> SELECT YEAR('1987-01-01');
            -> 1987
    
  • YEARWEEK(date), YEARWEEK(date,mode)YEARWEEK(date), YEARWEEK(date,mode)

    返回日期的年份和周数。结果中的年份在一年中的第一周和最后一周可能与日期参数中的年份不同。如果date为NULL,则返回NULL。Returns year and week for a date. The year in the result may be different from the year in the date argument for the first and the last week of the year. Returns NULL if date is NULL.

    mode 参数的作用与 WEEK() 的 mode 参数完全相同。对于单参数语法,使用 mode 值为 0。与 WEEK() 不同的是,default_week_format 的值不会影响 YEARWEEK()。The mode argument works exactly like the mode argument to WEEK(). For the single-argument syntax, a mode value of 0 is used. Unlike WEEK(), the value of default_week_format does not influence YEARWEEK().

    mysql> SELECT YEARWEEK('1987-01-01');
            -> 198652
    

    周数与 WEEK() 函数返回的结果不同(可选参数 0 或 1 时返回 0),因为 WEEK() 是以给定年份为上下文返回周数的。The week number is different from what the WEEK() function would return (0) for optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year.