YEAR() 函数可以从指定日期值中来获取年份值。语法格式如下:
YEAR(date);
YEAR() 函数返回的年份值范围为 1000 到 9999。
(1)获取当前日期的年份值,如下:
mysql> select YEAR(now()); +-------------+ | YEAR(now()) | +-------------+ | 2022 | +-------------+ 1 row in set (0.04 sec)
(2)获取指定日期字符串中的年份值,如下:
mysql> select YEAR('2022-04-25'); +--------------------+ | YEAR('2022-04-25') | +--------------------+ | 2022 | +--------------------+ 1 row in set (0.02 sec)
(3)如果指定的日期字符串参数不是一个合法的日期字符串,或者是NULL、空字符串,则直接返回 NULL。如下:
mysql> select YEAR(2022); +------------+ | YEAR(2022) | +------------+ | NULL | +------------+ 1 row in set (0.03 sec) mysql> select YEAR(NULL); +------------+ | YEAR(NULL) | +------------+ | NULL | +------------+ 1 row in set (0.03 sec) mysql> select YEAR(''); +----------+ | YEAR('') | +----------+ | NULL | +----------+ 1 row in set (0.02 sec)
(4)如果指定的日期字符串中没有日期部分,则返回 NULL。如下:
mysql> select YEAR('12:30:00'); +------------------+ | YEAR('12:30:00') | +------------------+ | NULL | +------------------+ 1 row in set (0.04 sec)
(5)如果日期为零,YEAR() 函数返回 0。如下:
mysql> select YEAR('0-0-0 12:30:00'); +------------------------+ | YEAR('0-0-0 12:30:00') | +------------------------+ | 0 | +------------------------+ 1 row in set (0.04 sec)