MySQL 常用日期与时间函数
日期函数
获得当前日期/时间
| Name | Synonym | Description |
|---|---|---|
CURRENT_DATE, CURRENT_DATE() |
CURDATE() |
Return the current date as 'YYYY-MM-DD' / YYYYMMDD |
CURRENT_TIME, CURRENT_TIME([fsp]) |
CURTIME([fsp]) |
Return the current time as 'hh:mm:ss' / hhmmssThe value is expressed in the session time zone. |
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP([fsp])LOCALTIME, LOCALTIME([fsp])LOCALTIMESTAMP, LOCALTIMESTAMP([fsp]) |
NOW([fsp]) |
Return the current date and time as 'YYYY-MM-DD hh:mm:ss' / YYYYMMDDhhmmssThe value is expressed in the session time zone. |
UTC_DATE, UTC_DATE() |
Return the current UTC date as 'YYYY-MM-DD' / YYYYMMDD |
|
UTC_TIME, UTC_TIME([fsp]) |
Return the current UTC time as 'hh:mm:ss' / hhmmss |
|
UTC_TIMESTAMP, UTC_TIMESTAMP([fsp]) |
Return the current UTC date and time as 'YYYY-MM-DD hh:mm:ss' / YYYYMMDDhhmmss |
注意,MySQL 时间支持的最高存储精度为微秒:
1 秒(s) =
1,000 毫秒(ms) =
1,000,000 微秒(μs) =
1,000,000,000 纳秒(ns) =
1,000,000,000,000 皮秒(ps) =
1,000,000,000,000,000 飞秒(fs) =
1,000,000,000,000,000,000 仄秒(zs) =
1,000,000,000,000,000,000,000 幺秒(ys) =
1,000,000,000,000,000,000,000,000 渺秒(as)
1 微秒(μs) = 10^-6 秒(0.000,001,百万分之一秒)
1 毫秒(ms) = 10^-3 秒(0.001,千分之一秒)
因此 fsp 参数范围只能为 0 ~ 6:
If the
fspargument is given to specify a fractional seconds precision from 0 to 6, the return value includes a fractional seconds part of that many digits.
例子:
1 | SELECT CURDATE(); -- 2018-08-08,获取当前年月日 |
时区查看/修改
5.1.13 MySQL Server Time Zone Support
查看当前时区
1 | -- 结果主要看 system_time_zone |
修改时区
通过 SQL SET 语法临时修改:
1 | -- 设置 Global 全局时区,重启后失效 |
通过修改配置文件,重启后永久生效:
1 | $ vim /etc/mysql/my.cnf |
时区转换 函数
CONVERT_TZ(dt, from_tz, to_tz) 函数用于将 DATETIME 类型转为指定时区,例如:
1 | -- TIMESTAMP 类型 |
1 | -- DATETIME 类型 |
TIMESTAMP 类型的时区显示,参考:https://dev.mysql.com/doc/refman/5.7/en/datetime.html
MySQL converts
TIMESTAMPvalues from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such asDATETIME.) By default, the current time zone for each connection is the server’s time. The time zone can be set on a per-connection basis. As long as the time zone setting remains constant, you get back the same value you store. If you store aTIMESTAMPvalue, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored. This occurs because the same time zone was not used for conversion in both directions. The current time zone is available as the value of thetime_zonesystem variable. For more information, see Section 5.1.13, “MySQL Server Time Zone Support”.
日期/时间类型转换 函数
TIMESTAMP → xxx
FROM_UNIXTIME(unix_timestamp[,format])
Returns a representation of
unix_timestampas aDATETIMEorVARCHARvalue. The value returned is expressed using the session time zone. (Clients can set the session time zone as described in Section 5.1.13, “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.
unix_timestamp
- When
unix_timestampis an integer, the fractional seconds precision of theDATETIMEis0.- When
unix_timestampis a decimal value, the fractional seconds precision of theDATETIMEis the same as the precision of the decimal value, up to a maximum of6.- When
unix_timestampis a floating point number, the fractional seconds precision of the datetime is6.
format
例子:
1 | -- 不指定 format 格式,返回 DATETIME 类型 |
fomart 参数参考这里。
xxx → TIMESTAMP
Return a Unix timestamp.
If no
dateargument, it returns a Unix timestamp representing seconds since'1970-01-01 00:00:00'UTC.If with a
dateargument, it returns the value of the argument as seconds since'1970-01-01 00:00:00'UTC.The server interprets
dateas 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 5.1.13, “MySQL Server Time Zone Support”.)The
dateargument may be
- a
DATE,DATETIME, orTIMESTAMPstring,- or a number in
YYMMDD,YYMMDDhhmmss,YYYYMMDD, orYYYYMMDDhhmmssformat.If the argument includes a time part, it may optionally include a fractional seconds part.
The return value is
- an integer if no argument is given or the argument does not include a fractional seconds part,
- or
DECIMALif an argument is given that includes a fractional seconds part.When the
dateargument is aTIMESTAMPcolumn,UNIX_TIMESTAMP()returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.The valid range of argument values is the same as for the
TIMESTAMPdata type:'1970-01-01 00:00:01.000000'UTC to'2038-01-19 03:14:07.999999'UTC. If you pass an out-of-range date toUNIX_TIMESTAMP(), it returns0.
例子:
1 | -- 1218124800,获取当前时间戳 |
DATETIME → String
Date/Time to Str(日期/时间转换为字符串)函数:
DATE_FORMAT(date, format)、TIME_FORMAT(time, format)
例子:
1 | select date_format(now(), '%Y-%m-%d'); -- 2018-08-08 |
String → DATETIME
This is the inverse of the
DATE_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. If the date, time, or datetime value extracted fromstris illegal,STR_TO_DATE()returnsNULLand produces a warning.
例子:
1 | select str_to_date('08/09/2008', '%m/%d/%Y'); -- 2008-08-09 |
format 参数
format 参数如下,这里只列出常用的。更多 format 参数参考:
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
format |
描述 |
|---|---|
%Y |
Year, numeric, four digits |
%y |
Year, numeric (two digits) |
%M |
Month name (January..December) |
%m |
Month, numeric (00..12) |
%D |
Day of the month with English suffix (0th, 1st, 2nd, 3rd, …) |
%d |
Day of the month, numeric (00..31) |
%H |
Hour (00..23) |
%h |
Hour (01..12) |
%i |
Minutes, numeric (00..59) |
%s |
Seconds (00..59) |
%f |
Microseconds (000000..999999) |
%T |
Time, 24-hour (hh:mm:ss) |
%r |
Time, 12-hour (hh:mm:ss followed by AM or PM) |
日期/时间计算 函数
为日期增加一个时间间隔:date_add()
为日期减去一个时间间隔:date_sub()
1 | set @dt = now(); |
日期/时间截取 函数
选取日期时间的各个部分:日期、时间、年、季度、月、日、小时、分钟、秒、微秒
1 | set @dt = now(); |
例子
按年/月/日/时统计订单量
按年统计:DATE_FORMAT(create_time,'%Y')
按月统计:DATE_FORMAT(create_time,'%Y-%m')
按日统计:DATE_FORMAT(create_time,'%Y-%m-%d')
按时统计:DATE_FORMAT(create_time,'%Y-%m-%d %H:00:00')
按日统计订单量,如下:
1 | select count(*), DATE_FORMAT(create_time,'%Y-%m-%d') AS days |
按 N 分钟统计订单量
做法在于将每行的分钟数 MINUTE(create_time) 除以 10 得到的小数使用 FLOOR 函数向下取整,再乘以 10 得到的就是所属区间。例如:
- 1 分钟 -> 0
- 25 分钟 -> 20
- 59 分钟 -> 50
下例按 10 分钟统计订单量:
1 | SELECT COUNT(*), DATE_FORMAT( |
参考
https://dev.mysql.com/doc/refman/5.7/en/functions.html
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html
https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html