EverKB

Knowledge Base Ever

在MySQL中對日期和時間加上或減去指定的時間間隔的函數

2019-11-21 14:41:36

標籤: MySQL, SQL Date Funcitons, DATE_ADD, DATE_SUB, ADDDATE, SUBDATE, INTERVAL, MySQL日期函數,MySQL日期加減

從編程語言的視角來說,日期和時間相對於整數和字符串是相對複雜和高級的數據類型,各種語言中的用法都不太統一。

本文主要講解MySQL中對日期和時間加上或將去指定的時間間隔的函數,加法使用DATE_ADD(),減法使用DATE_SUB()

DATE_ADD和DATE_SUB

SELECT DATE_ADD('2019-11-11', INTERVAL 2 MONTH);
SELECT DATE_SUB('2019-11-11', INTERVAL 2 MONTH);

還有ADDDATE和SUBDATE

SELECT ADDDATE('2019-11-11', INTERVAL 2 MONTH);
SELECT SUBDATE('2019-11-11', INTERVAL 2 MONTH);
這兩個函數除了可以省略INTERVAL以外,與DATE_ADD和DATE_SUB兩個函數完全一致。

以下是幾個簡單例子:

其中的INTERVAL 2 MONTH就是時間間隔,INTERVAL是固定字符,2是數量,MONTH是間隔類型,全部類型如下:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
還支持更複雜的間隔,對應的格式如下:
SECOND_MICROSECOND	'SECONDS.MICROSECONDS'
MINUTE_MICROSECOND	'MINUTES:SECONDS.MICROSECONDS'
MINUTE_SECOND	'MINUTES:SECONDS'
HOUR_MICROSECOND	'HOURS:MINUTES:SECONDS.MICROSECONDS'
HOUR_SECOND	'HOURS:MINUTES:SECONDS'
HOUR_MINUTE	'HOURS:MINUTES'
DAY_MICROSECOND	'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'
DAY_SECOND	'DAYS HOURS:MINUTES:SECONDS'
DAY_MINUTE	'DAYS HOURS:MINUTES'
DAY_HOUR	'DAYS HOURS'
YEAR_MONTH	'YEARS-MONTHS'

標籤

CentOS7 CentOS PHP Linux Python Python3 MySQL MariaDB YUM JavaScript mysql_native_password PHP7 CSS Redis MySQL8 caching_sha2_password HTML Bluetooth Failed to build these modules: _ctypes Minimal ISO substr date sub INTERVAL PECL SQL Date Funcitons Wi-Fi CodeIgniter font-size root Tag Cloud apache httpd dual network interfaces Laravel ss5 CURLFille horiz-align node.js ShadowsocksR vertical-align BarManager exec mb_substr PyCharm SUBDATE date add IntelliJIDEA PEAR SOCKS5 Proxy Server WebStorm Chrome find remi Tag Apache du jQuery PHP5.5 src cURL hide nginx Shadowsocks-Python V2Ray availability eth0 MariaDB10.4 PostgreSQL sub folder date Install MongoDB pdo_sqlsrv SOCKS5 Web Server File Upload mssql-tools register_shutdown_function Symfony ADDDATE DevExpress JetBrain php-fpm sqlsrv Zend Framework height network interface Shadowsocks-Libev unixODBC-devel Aura error_get_last Port 80 string data INDENTIFIED BY password policy requirements SOCKS Web Development Fedora Media Writer msodbcsql Redis5 SVN absolute Deepin jemalloc SQLAlchemy convert FuelPHP mysqlclient Shadowsocks toggle at-symbol Error Control Operator margin PHPUnit Framework ss5.passwd daemon process IIS password SOCKET vps center Fatal Errors MongoDB4 sudoers .htaccess DATE_SUB Phalcon SQL Server 2017 WiFi Compiling PHP frequency conflict set_error_handler TestCase apr Elasticsearch7.3 PHPUnit ss5.conf daemon HTTP particles.js Slim Vincent Garreau Failed to build these modules: _uuid MongoDB Sudo DATE_ADD ip command pg_bha.conf SQL Server width Compiling Apache Frameworks MySQL-python scrollbar Tcp BBR Apache2.4 Elasticsearch libpython3.7m.so.1.0 PHPStorm ss5-3.8.9 CURLOPT_POSTFIELDS NodeJs show VIM