本节介绍可用于操作时间值的函数。有关每种日期和时间类型的值范围以及可指定值的有效格式的描述,请参见 第 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->somethingFROMtbl_nameWHERE 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,INTERVALexprunit)ADDDATE(date,days)当第二个参数使用
INTERVAL形式调用时,ADDDATE()是DATE_ADD()的同义词。相关函数SUBDATE()是DATE_SUB()的同义词。有关INTERVALunit参数的信息,请参见 时间间隔。When invoked with theINTERVALform of the second argument,ADDDATE()is a synonym forDATE_ADD(). The related functionSUBDATE()is a synonym forDATE_SUB(). For information on theINTERVALunitargument, 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 thedaysform of the second argument, MySQL treats it as an integer number of days to be added toexpr.mysql>
SELECT ADDDATE('2008-01-02', 31);-> '2008-02-02'如果
date或days为NULL,则此函数返回NULL。This function returnsNULLifdateordaysisNULL.ADDTIME()将expr2加到expr1并返回结果。expr1是时间或日期时间表达式,expr2是时间表达式。如果expr1或expr2为NULL,则返回NULL。ADDTIME()addsexpr2toexpr1and returns the result.expr1is a time or datetime expression, andexpr2is a time expression. ReturnsNULLifexpr1orexpr2isNULL.该函数和
SUBTIME()函数的返回类型如下确定:The return type of this function and of theSUBTIME()function is determined as follows:如果第一个参数是动态参数(例如在预处理语句中),返回类型为
TIME。If the first argument is a dynamic parameter (such as in a prepared statement), the return type isTIME.否则,函数的解析类型由第一个参数的解析类型推导得出。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指定的时区,并返回结果值。时区的指定方式如 第 7.1.15 节,“MySQL 服务器时区支持” 所述。如果任何参数无效,或任何参数为NULL,则此函数返回NULL。CONVERT_TZ()converts a datetime valuedtfrom the time zone given byfrom_tzto the time zone given byto_tzand returns the resulting value. Time zones are specified as described in Section 7.1.15, “MySQL Server Time Zone Support”. This function returnsNULLif any of the arguments are invalid, or if any of them areNULL.在 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 theTIMESTAMPtype (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 fromfrom_tzto 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”.根据函数是在字符串还是数字上下文中使用,返回当前日期,格式为
'或YYYY-MM-DD'YYYYMMDD。Returns the current date as a value in'orYYYY-MM-DD'YYYYMMDDformat, depending on whether the function is used in string or numeric context.mysql>
SELECT CURDATE();-> '2008-06-13' mysql>SELECT CURDATE() + 0;-> 20080613CURRENT_DATE和CURRENT_DATE()是CURDATE()的同义词。CURRENT_DATEandCURRENT_DATE()are synonyms forCURDATE().CURRENT_TIME,CURRENT_TIME([fsp])CURRENT_TIME和CURRENT_TIME()是CURTIME()的同义词。CURRENT_TIMEandCURRENT_TIME()are synonyms forCURTIME().CURRENT_TIMESTAMP,CURRENT_TIMESTAMP([fsp])CURRENT_TIMESTAMP和CURRENT_TIMESTAMP()是NOW()的同义词。CURRENT_TIMESTAMPandCURRENT_TIMESTAMP()are synonyms forNOW().根据函数在字符串或数字上下文中使用的不同,返回当前时间,格式为
'hh:mm:ss'或hhmmss。该值以会话时区表示。Returns the current time as a value in'hh:mm:ss'orhhmmssformat, 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 thefspargument 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 | +--------------+提取日期或日期时间表达式
expr的日期部分。如果expr为NULL,则返回NULL。Extracts the date part of the date or datetime expressionexpr. ReturnsNULLifexprisNULL.mysql>
SELECT DATE('2003-12-31 01:02:03');-> '2003-12-31'DATEDIFF()返回以天数表示的expr1−expr2,从一个日期到另一个日期。expr1和expr2是日期或日期时间表达式。计算中仅使用值的日期部分。DATEDIFF()returnsexpr1−expr2expressed as a value in days from one date to the other.expr1andexpr2are 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 returnsNULLifexpr1orexpr2isNULL.DATE_ADD(,date,INTERVALexprunit)DATE_SUB(date,INTERVALexprunit)这些函数用于日期运算。
date参数指定起始日期或日期时间值。expr是一个表达式,指定要加到或减去起始日期的时间间隔值。expr被作为字符串求值;它可以以-开头表示负时间间隔。unit是一个关键字,指示表达式应按照哪种单位来解释。These functions perform date arithmetic. Thedateargument specifies the starting date or datetime value.expris an expression specifying the interval value to be added or subtracted from the starting date.expris evaluated as a string; it may start with a-for negative intervals.unitis 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 ofunitspecifiers, the expected form of theexprargument for eachunitvalue, and rules for operand interpretation in temporal arithmetic, see Temporal Intervals.返回值取决于参数:The return value depends on the arguments:
如果
date为NULL,函数返回NULL。IfdateisNULL, the function returnsNULL.DATE如果参数date是DATE值且计算仅涉及YEAR,MONTH,以及DAY部分(即不包含时间部分)。DATEif thedateargument is aDATEvalue and your calculations involve onlyYEAR,MONTH, andDAYparts (that is, no time parts).TIME如果date参数是TIME值,并且计算仅涉及HOURS、MINUTES和SECONDS部分(即不涉及日期部分)。TIMEif thedateargument is aTIMEvalue and the calculations involve onlyHOURS,MINUTES, andSECONDSparts (that is, no date parts).DATETIME如果第一个参数是DATETIME(或TIMESTAMP)值,或者如果第一个参数是DATE且unit值使用HOURS、MINUTES或SECONDS,或者如果第一个参数是TIME类型且unit值使用YEAR、MONTH或DAY。DATETIMEif the first argument is aDATETIME(orTIMESTAMP) value, or if the first argument is aDATEand theunitvalue usesHOURS,MINUTES, orSECONDS, or if the first argument is of typeTIMEand theunitvalue usesYEAR,MONTH, orDAY.如果第一个参数是动态参数(例如,预准备语句的参数),当第二个参数是仅包含
YEAR、MONTH或DAY值的间隔时,其解析类型为DATE;否则,其类型为DATETIME。If the first argument is a dynamic parameter (for example, of a prepared statement), its resolved type isDATEif the second argument is an interval that contains some combination ofYEAR,MONTH, orDAYvalues only; otherwise, its type isDATETIME.
为了确保结果是
DATETIME,您可以使用CAST()将第一个参数转换为DATETIME。To ensure that the result isDATETIME, you can useCAST()to convert the first argument toDATETIME.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 aMONTHinterval to aDATEorDATETIMEvalue, 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)根据
format字符串格式化date值。如果任一参数为NULL,函数返回NULL。Formats thedatevalue according to theformatstring. If either argument isNULL, the function returnsNULL.下表中显示的格式说明符可以在
format字符串中使用。格式说明符字符前必须加%字符。该说明符也适用于其他函数:STR_TO_DATE()、TIME_FORMAT()、UNIX_TIMESTAMP()。The specifiers shown in the following table may be used in theformatstring. 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)%pAM或PMAMorPM%r时间,12 小时制 ( hh:mm:ss后跟AM或PM)Time, 12-hour (hh:mm:ssfollowed byAMorPM)%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%xx,适用于上面未列出的任何 “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 thelc_time_namessystem variable (Section 12.16, “MySQL Server Locale Support”).对于
%U、%u、%V和%v说明符,请参阅WEEK()函数的描述,以获取关于模式值的信息。模式会影响周编号的方式。For the%U,%u,%V, and%vspecifiers, see the description of theWEEK()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 bycharacter_set_connectionandcollation_connectionso 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,INTERVALexprunit)请参阅
DATE_ADD()的描述。See the description forDATE_ADD().DAY()是DAYOFMONTH()的同义词。DAY()is a synonym forDAYOFMONTH().返回
date的星期名称。名称使用的语言由lc_time_names系统变量的值控制(见 第 12.16 节,“MySQL 服务器区域设置支持”)。如果date为NULL,则返回NULL。Returns the name of the weekday fordate. The language used for the name is controlled by the value of thelc_time_namessystem variable (see Section 12.16, “MySQL Server Locale Support”). ReturnsNULLifdateisNULL.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 fordate, in the range1to31, or0for dates such as'0000-00-00'or'2008-00-00'that have a zero day part. ReturnsNULLifdateisNULL.mysql>
SELECT DAYOFMONTH('2007-02-03');-> 3DAYOFWEEK(date)DAYOFWEEK(date)返回
date的星期索引(1= 星期日,2= 星期一,……,7= 星期六)。这些索引值对应 ODBC 标准。如果date为NULL,则返回NULL。Returns the weekday index fordate(1= Sunday,2= Monday, …,7= Saturday). These index values correspond to the ODBC standard. ReturnsNULLifdateisNULL.mysql>
SELECT DAYOFWEEK('2007-02-03');-> 7DAYOFYEAR(date)DAYOFYEAR(date)返回
date在一年中的第几天,范围为1到366。如果date为NULL,则返回NULL。Returns the day of the year fordate, in the range1to366. ReturnsNULLifdateisNULL.mysql>
SELECT DAYOFYEAR('2007-02-03');-> 34EXTRACT(unit FROM date)EXTRACT(unitFROMdate)EXTRACT()函数使用与DATE_ADD()或DATE_SUB()相同类型的unit指定符,但它从日期中提取部分内容,而不是执行日期运算。有关unit参数的信息,请参见 时间间隔。如果date为NULL,则返回NULL。TheEXTRACT()function uses the same kinds ofunitspecifiers asDATE_ADD()orDATE_SUB(), but extracts parts from the date rather than performing date arithmetic. For information on theunitargument, see Temporal Intervals. ReturnsNULLifdateisNULL.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给定一个天数
N,返回一个DATE值。如果N为NULL,则返回NULL。Given a day numberN, returns aDATEvalue. ReturnsNULLifNisNULL.mysql>
SELECT FROM_DAYS(730669);-> '2000-07-03'在处理旧日期时使用
FROM_DAYS()时请谨慎。它不适用于格里高利历(1582 年)之前的日期值。详见 第 13.2.7 节,“MySQL 使用的历法”。UseFROM_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 ofunix_timestampas 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_timestampis an internal timestamp value representing seconds since'1970-01-01 00:00:00'UTC, such as produced by theUNIX_TIMESTAMP()function.如果省略
format,此函数将返回一个DATETIME值。Ifformatis omitted, this function returns aDATETIMEvalue.如果
unix_timestamp或format为NULL,此函数将返回NULL。Ifunix_timestamporformatisNULL, this function returnsNULL.如果
unix_timestamp是整数,则DATETIME的小数秒精度为零。当unix_timestamp是小数值时,DATETIME的小数秒精度与小数值的精度相同,最多为 6。当unix_timestamp是浮点数时,datetime 的小数秒精度为 6。Ifunix_timestampis an integer, the fractional seconds precision of theDATETIMEis zero. Whenunix_timestampis a decimal value, the fractional seconds precision of theDATETIMEis the same as the precision of the decimal value, up to a maximum of 6. Whenunix_timestampis 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 forunix_timestampis 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 forunix_timestampthan the effective maximum returns0.format用于按照用于DATE_FORMAT()函数的格式字符串的相同方式格式化结果。如果提供了format,返回的值是VARCHAR。formatis used to format the result in the same way as the format string used for theDATE_FORMAT()function. Ifformatis supplied, the value returned is aVARCHAR.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 useUNIX_TIMESTAMP()andFROM_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 theUNIX_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 theDATE_FORMAT()and theSTR_TO_DATE()functions.如果
format为NULL,则此函数返回NULL。IfformatisNULL, this function returnsNULL.第一个和第二个参数的可能值会产生几种可能的格式字符串(有关使用的说明符,请参见
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 theDATE_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相同。TIMESTAMPcan also be used as the first argument toGET_FORMAT(), in which case the function returns the same values as forDATETIME.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'返回
time的小时。返回值的范围对于一天中的时间值为0到23。然而,TIME值的范围实际上更大,因此HOUR可以返回大于23的值。如果time为NULL,则返回NULL。Returns the hour fortime. The range of the return value is0to23for time-of-day values. However, the range ofTIMEvalues actually is much larger, soHOURcan return values greater than23. ReturnsNULLiftimeisNULL.mysql>
SELECT HOUR('10:05:03');-> 10 mysql>SELECT HOUR('272:59:59');-> 272获取日期或日期时间值,并返回对应月份的最后一天的值。如果参数无效或为
NULL,则返回NULL。Takes a date or datetime value and returns the corresponding value for the last day of the month. ReturnsNULLif the argument is invalid orNULL.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');-> NULLLOCALTIME和LOCALTIME()是NOW()的同义词。LOCALTIMEandLOCALTIME()are synonyms forNOW().LOCALTIMESTAMP,LOCALTIMESTAMP([fsp])LOCALTIMESTAMP和LOCALTIMESTAMP()是NOW()的同义词。LOCALTIMESTAMPandLOCALTIMESTAMP()are synonyms forNOW().根据年份和年日值返回一个日期。
dayofyear必须大于 0,否则结果为NULL。如果任一参数为NULL,结果也为NULL。Returns a date, given year and day-of-year values.dayofyearmust be greater than 0 or the result isNULL. The result is alsoNULLif either argument isNULL.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返回从
hour、minute和second参数计算得出的时间值。如果任何参数为NULL,则返回NULL。Returns a time value calculated from thehour,minute, andsecondarguments. ReturnsNULLif any of its arguments areNULL.second参数可以包含小数部分。Thesecondargument can have a fractional part.mysql>
SELECT MAKETIME(12,15,30);-> '12:15:30'Returns the microseconds from the time or datetime expression
expras a number in the range from0到999999. ReturnsNULL返回exprisNULL.Returns the microseconds from the time or datetime expressionexpras a number in the range from0to999999. ReturnsNULLifexprisNULL.mysql>
SELECT MICROSECOND('12:00:00.123456');-> 123456 mysql>SELECT MICROSECOND('2019-12-31 23:59:59.000010');-> 10Returns the minute for
time, in the range0到59,或NULL返回timeisNULL.Returns the minute fortime, in the range0to59, orNULLiftimeisNULL.mysql>
SELECT MINUTE('2008-02-03 10:05:03');-> 5返回
date的月份,范围为1到12,对应一月至十二月,或对于月份为零的日期如'0000-00-00'或'2008-00-00'返回0。如果date为NULL,则返回NULL。Returns the month fordate, in the range1to12for January to December, or0for dates such as'0000-00-00'or'2008-00-00'that have a zero month part. ReturnsNULLifdateisNULL.mysql>
SELECT MONTH('2008-02-03');-> 2MONTHNAME(date)MONTHNAME(date)返回
date的月份全名。月份名称使用的语言由系统变量lc_time_names的值控制(第 12.16 节,“MySQL 服务器本地化支持”)。如果date是NULL,则返回NULL。Returns the full name of the month fordate. The language used for the name is controlled by the value of thelc_time_namessystem variable (Section 12.16, “MySQL Server Locale Support”). ReturnsNULLifdateisNULL.mysql>
SELECT MONTHNAME('2008-02-03');-> 'February'返回当前日期和时间,格式为
'YYYY-MM-DD hh:mm:ss'或YYYYMMDDhhmmss,具体取决于函数是在字符串还是数字环境中使用。该值以会话时区表示。Returns the current date and time as a value in'orYYYY-MM-DD hh:mm:ss'YYYYMMDDhhmmssformat, 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 thefspargument 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.000000NOW()返回一个恒定的时间,表示语句开始执行时的时间。(在存储函数或触发器中,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 forSYSDATE(), 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, theSET TIMESTAMPstatement affects the value returned byNOW()but not bySYSDATE(). This means that timestamp settings in the binary log have no effect on invocations ofSYSDATE(). Setting the timestamp to a nonzero value causes each subsequent invocation ofNOW()to return that value. Setting the timestamp to zero cancels this effect so thatNOW()once again returns the current date and time.有关两个函数之间差异的更多信息,请参阅
SYSDATE()的描述。See the description forSYSDATE()for additional information about the differences between the two functions.在周期
P(格式为YYMM或YYYYMM)中加上N个月。返回值格式为YYYYMM。AddsNmonths to periodP(in the formatYYMMorYYYYMM). Returns a value in the formatYYYYMM.Note周期参数
P不是 日期值。The period argumentPis not a date value.如果
P或N为NULL,此函数将返回NULL。This function returnsNULLifPorNisNULL.mysql>
SELECT PERIOD_ADD(200801,2);-> 200803Returns the number of months between periods
P1以及P2.P1以及P2should be in the formatYYMM或者YYYYMM. Note that the period argumentsP1以及P2are 在多线程系统中 date values.Returns the number of months between periodsP1andP2.P1andP2should be in the formatYYMMorYYYYMM. Note that the period argumentsP1andP2are not date values.如果
P1或P2是NULL,此函数将返回NULL。This function returnsNULLifP1orP2isNULL.mysql>
SELECT PERIOD_DIFF(200802,200703);-> 11返回
date所属年份的季度,范围从1到4,如果date是NULL,则返回NULL。Returns the quarter of the year fordate, in the range1to4, orNULLifdateisNULL.mysql>
SELECT QUARTER('2008-04-01');-> 2返回
time的秒数,范围为0到59,如果time为NULL则返回NULL。Returns the second fortime, in the range0to59, orNULLiftimeisNULL.mysql>
SELECT SECOND('10:05:03');-> 3返回将
seconds参数转换为小时、分钟和秒的TIME值。结果的范围受TIME数据类型的限制。如果参数对应的值超出该范围,则会产生警告。Returns thesecondsargument, converted to hours, minutes, and seconds, as aTIMEvalue. The range of the result is constrained to that of theTIMEdata type. A warning occurs if the argument corresponds to a value outside that range.如果
seconds是NULL,该函数将返回NULL。The function returnsNULLifsecondsisNULL.mysql>
SELECT SEC_TO_TIME(2378);-> '00:39:38' mysql>SELECT SEC_TO_TIME(2378) + 0;-> 3938这是
DATE_FORMAT()函数的逆函数。它接收一个字符串str和一个格式字符串format。STR_TO_DATE()会返回一个DATETIME值,如果格式字符串同时包含日期和时间部分;如果字符串只包含日期或时间部分,则返回DATE或TIME值。如果str或format为NULL,则函数返回NULL。如果从str中提取的日期、时间或日期时间值无法按照服务器遵循的规则解析,STR_TO_DATE()将返回NULL并产生警告。This is the inverse of theDATE_FORMAT()function. It takes a stringstrand a format stringformat.STR_TO_DATE()returns aDATETIMEvalue if the format string contains both date and time parts, or aDATEorTIMEvalue if the string contains only date or time parts. IfstrorformatisNULL, the function returnsNULL. If the date, time, or datetime value extracted fromstrcannot be parsed according to the rules followed by the server,STR_TO_DATE()returnsNULLand produces a warning.服务器扫描
str,尝试将format与之匹配。格式字符串可以包含文字字符和以%开头的格式说明符。format中的文字字符必须在str中逐字匹配。format中的格式说明符必须匹配str中的日期或时间部分。有关可以在format中使用的说明符,请参阅DATE_FORMAT()函数说明。The server scansstrattempting to matchformatto it. The format string can contain literal characters and format specifiers beginning with%. Literal characters informatmust match literally instr. Format specifiers informatmust match a date or time part instr. For the specifiers that can be used informat, see theDATE_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 ofstrand fails ifformatis found not to match. Extra characters at the end ofstrare 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 instrproduce 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_DATESQL 模式,则不允许使用零日期。在这种情况下,STR_TO_DATE()会返回NULL并生成警告:If theNO_ZERO_DATESQL mode is enabled, zero dates are disallowed. In that case,STR_TO_DATE()returnsNULLand 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')returns2023-02-31. Enabling or disabling theALLOW_INVALID_DATESserver SQL mode has no effect on this behavior. See Section 13.2.2, “The DATE, DATETIME, and TIMESTAMP Types”, for more information.SUBDATE(,date,INTERVALexprunit)SUBDATE(expr,days)当以第二个参数的
INTERVAL形式调用时,SUBDATE()是DATE_SUB()的同义词。有关INTERVALunit参数的信息,请参阅DATE_ADD()的讨论。When invoked with theINTERVALform of the second argument,SUBDATE()is a synonym forDATE_SUB(). For information on theINTERVALunitargument, see the discussion forDATE_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 fordays. In such cases, it is interpreted as the number of days to be subtracted from the date or datetime expressionexpr.mysql>
SELECT SUBDATE('2008-01-02 12:00:00', 31);-> '2007-12-02 12:00:00'如果其任何参数为
NULL,此函数将返回NULL。This function returnsNULLif any of its arguments areNULL.SUBTIME()返回以与expr1相同格式表示的expr1−expr2的值。expr1是时间或日期时间表达式,而expr2是时间表达式。SUBTIME()returnsexpr1−expr2expressed as a value in the same format asexpr1.expr1is a time or datetime expression, andexpr2is a time expression.此函数返回类型的解析方式与
ADDTIME()函数的解析方式相同;有关更多信息,请参阅该函数的说明。Resolution of this function's return type is performed as it is for theADDTIME()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 returnsNULLifexpr1orexpr2isNULL.返回当前日期和时间,格式为
'YYYY-MM-DD hh:mm:ss'或YYYYMMDDhhmmss,取决于该函数是在字符串还是数字上下文中使用。Returns the current date and time as a value in'orYYYY-MM-DD hh:mm:ss'YYYYMMDDhhmmssformat, depending on whether the function is used in string or numeric context.如果提供了
fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If thefspargument 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 forNOW(), 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, theSET TIMESTAMPstatement affects the value returned byNOW()but not bySYSDATE(). This means that timestamp settings in the binary log have no effect on invocations ofSYSDATE().因为
SYSDATE()即使在同一条语句中也可能返回不同的值,并且不受SET TIMESTAMP影响,所以它是非确定性的,因此如果使用基于语句的二进制日志,它在复制中是不安全的。如果这是一个问题,你可以使用基于行的日志。BecauseSYSDATE()can return different values even within the same statement, and is not affected bySET 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-nowoption to causeSYSDATE()to be an alias forNOW(). This works if the option is used on both the replication source server and the replica.SYSDATE()的非确定性特性也意味着在计算引用它的表达式时无法使用索引。The nondeterministic nature ofSYSDATE()also means that indexes cannot be used for evaluating expressions that refer to it.提取时间或日期时间表达式
expr的时间部分,并将其作为字符串返回。如果expr为NULL,则返回NULL。Extracts the time part of the time or datetime expressionexprand returns it as a string. ReturnsNULLifexprisNULL.该函数在基于语句的复制中不安全。如果在
binlog_format设置为STATEMENT时使用此函数,将记录一个警告。This function is unsafe for statement-based replication. A warning is logged if you use this function whenbinlog_formatis set toSTATEMENT.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的时间值。expr1和expr2是字符串,会被转换为TIME或DATETIME表达式;转换后必须属于同一类型。如果expr1或expr2为NULL,则返回NULL。TIMEDIFF()returnsexpr1−expr2expressed as a time value.expr1andexpr2are strings which are converted toTIMEorDATETIMEexpressions; these must be of the same type following conversion. ReturnsNULLifexpr1orexpr2isNULL.TIMEDIFF()返回的结果限制在TIME值允许的范围内。或者,你可以使用TIMESTAMPDIFF()和UNIX_TIMESTAMP()中的任意一个函数,它们都返回整数。The result returned byTIMEDIFF()is limited to the range allowed forTIMEvalues. Alternatively, you can use either of the functionsTIMESTAMPDIFF()andUNIX_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 expressionexpras a datetime value. With two arguments, it adds the time expressionexpr2to the date or datetime expressionexpr1and returns the result as a datetime value. ReturnsNULLifexpr,expr1, orexpr2isNULL.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 expressionintervalto the date or datetime expressiondatetime_expr. The unit forintervalis given by theunitargument, which should be one of the following values:MICROSECOND(microseconds),SECOND,MINUTE,HOUR,DAY,WEEK,MONTH,QUARTER, orYEAR.可以使用所示的关键字之一指定
unit值,或者使用SQL_TSI_前缀。例如,DAY和SQL_TSI_DAY都是合法的。Theunitvalue may be specified using one of keywords as shown, or with a prefix ofSQL_TSI_. For example,DAYandSQL_TSI_DAYboth are legal.如果
interval或datetime_expr为NULL,则此函数返回NULL。This function returnsNULLifintervalordatetime_exprisNULL.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 aMONTHinterval to aDATEorDATETIMEvalue, 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()函数描述中列出的值相同。Returnsdatetime_expr2−datetime_expr1, wheredatetime_expr1anddatetime_expr2are 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 theunitargument. The legal values forunitare the same as those listed in the description of theTIMESTAMPADD()function.如果
datetime_expr1或datetime_expr2为NULL,此函数将返回NULL。This function returnsNULLifdatetime_expr1ordatetime_expr2isNULL.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');-> 128885Note此函数的日期或日期时间参数顺序与使用 2 个参数调用
TIMESTAMP()函数时的顺序相反。The order of the date or datetime arguments for this function is the opposite of that used with theTIMESTAMP()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 theDATE_FORMAT()function, but theformatstring may contain format specifiers only for hours, minutes, seconds, and microseconds. Other specifiers produce aNULLor0.TIME_FORMAT()returnsNULLiftimeorformatisNULL.如果
time值包含的小时部分大于23,则%H和%k小时格式说明符会生成大于通常0..23范围的值。其他小时格式说明符会生成小时值对 12 取模的结果。If thetimevalue contains an hour part that is greater than23, the%Hand%khour format specifiers produce a value larger than the usual range of0..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 thetimeargument, converted to seconds. ReturnsNULLiftimeisNULL.mysql>
SELECT TIME_TO_SEC('22:23:00');-> 80580 mysql>SELECT TIME_TO_SEC('00:39:38');-> 2378给定一个日期
date,返回日数编号(自公元 0 年以来的天数)。如果date为NULL,则返回NULL。Given a datedate, returns a day number (the number of days since year 0). ReturnsNULLifdateisNULL.mysql>
SELECT TO_DAYS(950501);-> 728779 mysql>SELECT TO_DAYS('2007-10-07');-> 733321TO_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_DATESSQL 服务器模式,这都是正确的。This is true whether or not theALLOW_INVALID_DATESSQL server mode is enabled.TO_SECONDS(expr)TO_SECONDS(expr)给定一个日期或日期时间
expr,返回从公元 0 年起的秒数。如果expr不是有效的日期或日期时间值(包括NULL),则返回NULL。Given a date or datetimeexpr, returns the number of seconds since the year 0. Ifexpris not a valid date or datetime value (includingNULL), it returnsNULL.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 使用的日历”。LikeTO_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 节,“日期和时间数据类型” 中的规则,将日期中的两位数年份转换为四位数形式。LikeTO_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_DATESSQL 服务器模式,这都是正确的。This is true whether or not theALLOW_INVALID_DATESSQL server mode is enabled.UNIX_TIMESTAMP([date])UNIX_TIMESTAMP([date])如果调用
UNIX_TIMESTAMP()时没有提供date参数,它将返回一个 Unix 时间戳,表示自'1970-01-01 00:00:00'UTC 起的秒数。IfUNIX_TIMESTAMP()is called with nodateargument, 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格式的数字。如果参数包含时间部分,它可以选择性地包含秒的小数部分。IfUNIX_TIMESTAMP()is called with adateargument, it returns the value of the argument as seconds since'1970-01-01 00:00:00'UTC. The server interpretsdateas 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”.) Thedateargument may be aDATE,DATETIME, orTIMESTAMPstring, or a number inYYMMDD,YYMMDDhhmmss,YYYYMMDD, orYYYYMMDDhhmmssformat. 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, orDECIMALif an argument is given that includes a fractional seconds part.当
date参数是TIMESTAMP列时,UNIX_TIMESTAMP()直接返回内部时间戳值,不进行隐式的 “字符串转 Unix 时间戳” 转换。When thedateargument is aTIMESTAMPcolumn,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 theTIMESTAMPdata 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 forUNIX_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 toUNIX_TIMESTAMP(), it returns0. IfdateisNULL, it returnsNULL.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 useUNIX_TIMESTAMP()andFROM_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 forUNIX_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 theMETtime 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 subtractUNIX_TIMESTAMP()columns, you might want to cast them to signed integers. See Section 14.10, “Cast Functions and Operators”.返回当前 UTC 日期,格式为
'或YYYY-MM-DD'YYYYMMDD,取决于该函数是在字符串上下文还是数字上下文中使用。Returns the current UTC date as a value in'orYYYY-MM-DD'YYYYMMDDformat, depending on whether the function is used in string or numeric context.mysql>
SELECT UTC_DATE(), UTC_DATE() + 0;-> '2003-08-14', 20030814根据函数是在字符串还是数字上下文中使用,返回当前 UTC 时间,格式为
'hh:mm:ss'或hhmmss。Returns the current UTC time as a value in'hh:mm:ss'orhhmmssformat, depending on whether the function is used in string or numeric context.如果提供了
fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If thefspargument 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.000000UTC_TIMESTAMP,UTC_TIMESTAMP([fsp])返回当前的 UTC 日期和时间,作为
'YYYY-MM-DD hh:mm:ss'或YYYYMMDDhhmmss格式的值,具体取决于该函数是在字符串上下文还是数字上下文中使用。Returns the current UTC date and time as a value in'orYYYY-MM-DD hh:mm:ss'YYYYMMDDhhmmssformat, depending on whether the function is used in string or numeric context.如果提供了
fsp参数来指定 0 到 6 的秒分数精度,则返回值将包含具有相应位数的秒小数部分。If thefspargument 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.000000WEEK(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 fordate. The two-argument form ofWEEK()enables you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from0to53or from1to53. If themodeargument is omitted, the value of thedefault_week_formatsystem variable is used. See Section 7.1.8, “Server System Variables”. For aNULLdate value, the function returnsNULL.下表描述了
mode参数的工作原理。The following table describes how themodeargument 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 编号:Formodevalues 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 returns0if you do not use2,3,6, or7as the optionalmodeargument:mysql>
SELECT YEAR('2000-01-01'), WEEK('2000-01-01',0);-> 2000, 0有人可能会争辩说,
WEEK()应该返回52,因为给定的日期实际上发生在 1999 年的第 52 周。然而,WEEK()返回0,以便返回值为 “指定年份中的周数。” 这样在与其他从日期中提取日期部分的函数结合使用时,WEEK()函数是可靠的。One might argue thatWEEK()should return52because the given date actually occurs in the 52nd week of 1999.WEEK()returns0instead so that the return value is “the week number in the given year.” This makes use of theWEEK()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, use0,2,5, or7as the optionalmodeargument.mysql>
SELECT WEEK('2000-01-01',2);-> 52或者,使用
YEARWEEK()函数:Alternatively, use theYEARWEEK()function:mysql>
SELECT YEARWEEK('2000-01-01');-> 199952 mysql>SELECT MID(YEARWEEK('2000-01-01'),5,2);-> '52'返回
date的星期索引(0= 星期一,1= 星期二,…6= 星期日)。如果date为NULL,则返回NULL。Returns the weekday index fordate(0= Monday,1= Tuesday, …6= Sunday). ReturnsNULLifdateisNULL.mysql>
SELECT WEEKDAY('2008-02-03 22:23:00');-> 6 mysql>SELECT WEEKDAY('2007-11-06');-> 1WEEKOFYEAR(date)WEEKOFYEAR(date)返回日期在日历年中的周数,范围从
1到53。如果date为NULL,则返回NULL。Returns the calendar week of the date as a number in the range from1to53. ReturnsNULLifdateisNULL.WEEKOFYEAR()是一个兼容性函数,相当于WEEK(。date,3)WEEKOFYEAR()is a compatibility function that is equivalent toWEEK(.date,3)mysql>
SELECT WEEKOFYEAR('2008-02-20');-> 8Returns the year for
date, in the range1000到9999,或0for the “零” date. ReturnsNULL返回dateisNULL.Returns the year fordate, in the range1000to9999, or0for the “zero” date. ReturnsNULLifdateisNULL.mysql>
SELECT YEAR('1987-01-01');-> 1987YEARWEEK(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. ReturnsNULLifdateisNULL.mode参数的作用与WEEK()的mode参数完全相同。对于单参数语法,使用mode值为 0。与WEEK()不同的是,default_week_format的值不会影响YEARWEEK()。Themodeargument works exactly like themodeargument toWEEK(). For the single-argument syntax, amodevalue of 0 is used. UnlikeWEEK(), the value ofdefault_week_formatdoes not influenceYEARWEEK().mysql>
SELECT YEARWEEK('1987-01-01');-> 198652周数与
WEEK()函数返回的结果不同(可选参数0或1时返回0),因为WEEK()是以给定年份为上下文返回周数的。The week number is different from what theWEEK()function would return (0) for optional arguments0or1, asWEEK()then returns the week in the context of the given year.