Date and time functions refer to functions used to analyze and process date values and time values in formulas. In this article, we will share with you a summary of MYSQL date functions.
See 7.3.6 Date and Time Types for a description of the range of values each type has and the valid formats for specifying date and time values.
Here is an example of using date functions. The following query selects all records whose date_col value is within the last 30 days:
mysql> SELECT something FROM table
WHERE TO_DAYS(NOW()) - TO_DAYS(date_col)
DAYOFWEEK(date)
Returns the week index of date (1=Sunday, 2=Monday, ...7=Saturday). These index values correspond to the ODBC standard.
mysql> select DAYOFWEEK('1998-02-03');
-> 3
WEEKDAY(date)
Returns the week index of date (0=Monday, 1= Tuesday, …6= Sunday).
mysql> select WEEKDAY('1997-10-04 22:23:00');
-> 5
mysql> select WEEKDAY('1997-11-05');
- > 2
DAYOFMONTH(date)
Returns the day of the month of date, in the range of 1 to 31.
mysql> select DAYOFMONTH('1998-02-03');
-> 3
DAYOFYEAR(date)
Returns the number of days of the year in date, between 1 and 366 within the range.
mysql> select DAYOFYEAR('1998-02-03');
-> 34
MONTH(date)
Returns the month of date, ranging from 1 to 12.
mysql> select MONTH('1998-02-03');
-> 2
DAYNAME(date)
Returns the day of the week name of date.
mysql> select DAYNAME("1998-02-05");
-> 'Thursday'
MONTHNAME(date)
Returns the month name of date.
mysql> select MONTHNAME("1998-02-05");
-> 'February'
QUARTER(date)
Returns the quarter of the year in date, ranging from 1 to 4.
mysql> select QUARTER('98-04-01');
-> 2
WEEK(date)
WEEK(date,first)
For Where Sunday is the first day of the week, there is a single argument that returns the week number of date, in the range 0 to 52. The 2 argument form WEEK() allows
you to specify whether the week starts on Sunday or Monday. If the second parameter is 0, the week starts on Sunday, if the second parameter is 1,
starts on Monday.
mysql> select WEEK('1998-02-20');
-> 7
mysql> select WEEK('1998-02-20',0);
-> 7
mysql> select WEEK('1998-02-20',1);
-> 8
YEAR(date)
Returns the year of date, ranging from 1000 to 9999.
mysql> select YEAR('98-02-03');
-> 1998
HOUR(time)
Returns the hour of time, ranging from 0 to 23.
mysql> select HOUR('10:05:03');
-> 10
MINUTE(time)
Returns the minute of time, ranging from 0 to 59.
mysql> select MINUTE('98-02-03 10:05:03');
-> 5
SECOND(time)
Returns the number of seconds of time, the range is 0 to 59.
mysql> select SECOND('10:05:03');
-> 3
PERIOD_ADD(P,N)
Add N months to stage P (in format YYMM or YYYYMM). Returns the value in the format YYYYMM. Note that the phase parameter P is not a date value.
mysql> select PERIOD_ADD(9801,2);
-> 199803
PERIOD_DIFF(P1,P2)
Returns the number of months between periods P1 and P2, P1 and P2 should In the format YYMM or YYYYMM. Note that the period parameters P1 and P2 are not date values.
mysql> select PERIOD_DIFF(9802,199703);
-> 11
DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
#ADDDATE(date,INTERVAL expr type)
SUBDATE(date,INTERVAL expr type)
These functions perform date operations. As of MySQL 3.22, they are new. ADDDATE() and SUBDATE() are synonyms of DATE_ADD() and DATE_SUB().
In MySQL 3.23, you can use + and - instead of DATE_ADD() and DATE_SUB(). (See example) date is a
DATETIME or DATE value that specifies the start date, expr is an expression that specifies the interval value to be added to or subtracted from the start date, expr is a string; it can start with
A "-" starts to indicate a negative interval. type is a keyword that specifies how the expression should be interpreted. The EXTRACT(type FROM date) function returns the "type" interval from date
. The following table shows how the type and expr parameters are related: type value meaning expected expr format
SECOND seconds SECONDS
MINUTE minutes MINUTES
HOUR time HOURS
DAY days DAYS
MONTH months MONTHS
YEAR YEARS
MINUTE_SECOND Minutes and seconds "MINUTES:SECONDS"
HOUR_MINUTE Hours and minutes "HOURS:MINUTES"
DAY_HOUR Days and hours "DAYS HOURS"
YEAR_MONTH Years and months "YEARS- MONTHS"
HOUR_SECOND hours, minutes, "HOURS:MINUTES:SECONDS"
DAY_MINUTE days, hours, minutes"DAYS HOURS:MINUTES"
DAY_SECOND days, hours, minutes, seconds"DAYS HOURS:MINUTES:SECONDS "
MySQL allows any punctuation delimiter in expr format. Indicates that recommended delimiters are displayed. If the date argument is a DATE value and your calculation is only
Contains YEAR, MONTH, and DAY components (that is, no time component), and the result is a DATE value. Otherwise the result is a DATETIME value.
mysql> SELECT "1997-12-31 23:59:59" + INTERVAL 1 SECOND;
-> 1998-01-01 00:00:00
mysql> SELECT INTERVAL 1 DAY + "1997-12-31";
-> 1998-01-01
mysql> SELECT "1998-01-01" - INTERVAL 1 SECOND;
-> 1997-12-31 23:59:59
mysql> SELECT DATE_ADD("1997-12-31 23:59:59",
INTERVAL 1 SECOND);
-> 1998-01-01 00:00:00
mysql> SELECT DATE_ADD("1997-12-31 23:59:59",
INTERVAL 1 DAY);
-> 1998-01-01 23:59:59
mysql> SELECT DATE_ADD("1997-12-31 23:59:59",
INTERVAL "1:1" MINUTE_SECOND);
-> 1998-01-01 00:01:00
mysql> SELECT DATE_SUB("1998-01-01 00:00:00",
INTERVAL "1 1:1:1" DAY_SECOND);
-> 1997-12-30 22:58:59
mysql> ; SELECT DATE_ADD("1998-01-01 00:00:00",
INTERVAL "-1 10" DAY_HOUR);
-> 1997-12-30 14:00:00
mysql> SELECT DATE_SUB("1998-01-02", INTERVAL 31 DAY);
-> 1997-12-02
mysql> SELECT EXTRACT(YEAR FROM "1999-07-02");
- > 1999
mysql> SELECT EXTRACT(YEAR_MONTH FROM "1999-07-02 01:02:03");
-> 199907
mysql> SELECT EXTRACT(DAY_MINUTE FROM "1999-07-02 01:02:03");
-> 20102
If you specify an interval value that is too short (excluding the interval expected by the type keyword), MySQL assumes that you omitted the interval value The leftmost part. For example,
If you specify a type of DAY_SECOND, the value expr is expected to have day, hour, minute, and second components. If you specify a value like "1:10",
MySQL assumes that the day and hour parts are missing and the value represents minutes and seconds. In other words, "1:10" DAY_SECOND is interpreted in a way that it is equivalent to "1:10" MINUTE_SECOND
, which is ambiguous with the way MySQL interprets the TIME value to represent an elapsed time rather than as a time of day. sex. If you use a really incorrect date,
the result is NULL. If you increment MONTH, YEAR_MONTH, or YEAR and the resulting date is greater than the maximum number of days in the new month, the days are adjusted to the maximum number of days in the new month.
mysql> select DATE_ADD('1998-01-30', Interval 1 month);
-> 1998-02-28
Note that the word INTERVAL from the previous example and type keywords are not case-sensitive.
TO_DAYS(date)
Given a date date, return a number of days (the number of days from year 0).
mysql> select TO_DAYS(950501);
-> 728779
mysql> select TO_DAYS('1997-10-07');
-> 729669
TO_DAYS( ) is not intended to be used using values before the advent of the Gregorian calendar (1582).
FROM_DAYS(N)
Given a number of days N, return a DATE value.
mysql> select FROM_DAYS(729669);
-> '1997-10-07'
TO_DAYS() is not intended to be used with values before the advent of the Gregorian calendar (1582) .
DATE_FORMAT(date,format)
Format the date value according to the format string. The following modifiers can be used in the format string: %M month name (January...December)
%W week name (Sunday...Saturday)
%D day of the month with English prefix (1st, 2nd, 3rd, etc.)
%Y Year, number, 4 digits
%y Year, number, 2 digits
%a Abbreviated day of the week name (Sun......Sat)
%d Number of days in the month, number (00……31)
%e Number of days in the month, number (0……31)
%m Month, number (01……12)
%c Month, Number (1...12)
%b Abbreviated month name (Jan...Dec)
%j Number of days in a year (001...366)
%H Hour (00...23)
%k hours (0...23)
%h hours (01...12)
%I hours (01...12)
%l hours (1...12)
%i minutes, number (00......59)
%r time, 12 hours (hh:mm:ss [AP]M)
%T time, 24 hours (hh:mm:ss)
%S seconds (00……59)
%s seconds (00……59)
%p AM or PM
%w The number of days in a week (0=Sunday…6=Saturday)
%U Week (0……52), where Sunday is the first day of the week
%u Week (0……52), where Monday is the first day of the week
%% A text "%".
All other characters are copied to the result without interpretation.
mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
-> 'Saturday October 1997'
mysql> select DATE_FORMAT('1997-10-04 22:23:00', '%H:%i:%s');
-> '22:23:00'
mysql> select DATE_FORMAT(' 1997-10-04 22:23:00',
'%D %y %a %d %m %b %j');
-> '4th 97 Sat 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'
In MySQL3.23, % is required before the format modifier character. In earlier versions of MySQL, % was optional.
TIME_FORMAT(time,format)
This is used like the DATE_FORMAT() function above, but the format string can only contain those format modifiers that handle hours, minutes, and seconds.
Other modifiers produce a NULL value or 0.
CURDATE()
CURRENT_DATE
Returns today's date value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context.
mysql> select CURDATE();
-> '1997-12-15'
mysql> select CURDATE() + 0;
-> 19971215
CURTIME( )
CURRENT_TIME
Returns the current time value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context.
mysql> select CURTIME();
-> '23:50:26'
mysql> select CURTIME() + 0;
-> 235026
NOW( )
SYSDATE()
CURRENT_TIMESTAMP
Returns the current date and time in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is in a character Strings are still used in the
context of numbers.
mysql> select NOW();
-> '1997-12-15 23:50:26'
mysql> select NOW() + 0;
-> 19971215235026
UNIX_TIMESTAMP()
UNIX_TIMESTAMP(date)
If called without parameters, returns a Unix timestamp (the number of seconds since '1970-01-01 00:00:00' GMT). If UNIX_TIMESTAMP() is called with a
date argument, it returns the number of seconds since '1970-01-01 00:00:00' GMT. date can be a DATE string, a DATETIME
string, a TIMESTAMP, or a number in local time in YYMMDD or YYYYMMDD format.
mysql> select UNIX_TIMESTAMP();
-> 882226357
mysql> select UNIX_TIMESTAMP('1997-10-04 22:23:00');
-> 875996580
When UNIX_TIMESTAMP is used for a TIMESTAMP column, the function will accept the value directly, without the implicit "string-to-unix-timestamp" transformation.
FROM_UNIXTIME(unix_timestamp)
Returns the value represented by the unix_timestamp parameter in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is in a string
or used in a numerical context.
mysql> select FROM_UNIXTIME(875996580);
-> '1997-10-04 22:23:00'
mysql> select FROM_UNIXTIME(875996580) + 0;
-> 19971004222300
FROM_UNIXTIME(unix_timestamp,format)
Returns a string representing the Unix time stamp, formatted according to the format string. format can contain the same modifiers as those listed for the DATE_FORMAT() function.
mysql> select FROM_UNIXTIME(UNIX_TIMESTAMP(),
'%Y %D %M %h:%i:%s %x');
-> '1997 23rd December 03:43:30 x'
SEC_TO_TIME(seconds)
Returns the seconds parameter, converted into hours, minutes and seconds. The value is formatted in 'HH:MM:SS' or HHMMSS, depending on whether the function is in a string or Used in the context of numbers
.
mysql> select SEC_TO_TIME(2378);
-> '00:39:38'
mysql> select SEC_TO_TIME(2378) + 0;
-> 3938
TIME_TO_SEC(time)
Return the time parameter and convert it into seconds.
mysql> select TIME_TO_SEC('22:23:00');
-> 80580
mysql> select TIME_TO_SEC('00:39:38');
-> 2378
Date functions and flexible use of function encapsulation
##Commonly used mysql date functionsMYSQL date function collectionThe above is the detailed content of MYSQL date function summary. For more information, please follow other related articles on the PHP Chinese website!

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

The main reasons for poor MySQL query performance include not using indexes, wrong execution plan selection by the query optimizer, unreasonable table design, excessive data volume and lock competition. 1. No index causes slow querying, and adding indexes can significantly improve performance. 2. Use the EXPLAIN command to analyze the query plan and find out the optimizer error. 3. Reconstructing the table structure and optimizing JOIN conditions can improve table design problems. 4. When the data volume is large, partitioning and table division strategies are adopted. 5. In a high concurrency environment, optimizing transactions and locking strategies can reduce lock competition.

In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.