Mysql's STR_TO_DATE and DATE_FORMAT functions
1. Available backgrounds:
-
DATE_FORMAT: Convert the date data in the database to the String type we want
-
STR_TO_DATE: It is necessary to convert the string in the specified time format to a value of type DATETIME according to the provided display format
2. Grammar:
-
date_format(date, format); Among them, date is the date data that needs to be converted, and format defines the conversion format.
-
str_to_date(str, format); where str is the string data to be converted, and format defines the conversion format.
Three, format format:
Format | describe |
---|---|
%a | abbreviated day of the week |
%b | abbreviated month name |
%c | month, value |
%D | day of month with english prefix |
%d | Day of the month, value (00-31) |
%e | Day of the month, value (0-31) |
%f | microsecond |
%H | hour (00-23) |
%h | hour (01-12) |
%I | hour (01-12) |
%i | minute, value (00-59) |
%j | Day of the year (001-366) |
%k | hour(0-23) |
%l | hours (1-12) |
%M | month name |
%m | month, value (00-12) |
%p | AM or PM |
%r | Time, 12-hour (hh:mm:ss AM or PM) |
%S | seconds (00-59) |
%s | seconds (00-59) |
%T | Time, 24-hour (hh:mm:ss) |
%U | Week (00-53) Sunday is the first day of the week |
%u | Week (00-53) Monday is the first day of the week |
%V | Week (01-53) Sunday is the first day of the week, used with %X |
%v | Week (01-53) Monday is the first day of the week, use with %x |
%W | week name |
%w | Day of the week (0=Sunday, 6=Saturday) |
%X | Year, where Sunday is the first day of the week, 4 digits, used with %V |
%x | Year, where Monday is the first day of the week, 4 digits, used with %v |
%Y | year, 4 digits |
%y | year, 2 digits |
4. Example:
DATE_FORMAT:
SELECT DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p');
SELECT DATE_FORMAT(NOW(),'%m-%d-%Y');
SELECT DATE_FORMAT(NOW(),'%d %b %y');
SELECT DATE_FORMAT(NOW(),'%d %b %Y %T:%f');
结果:
Oct 14 2021 04:18 PM
10-14-2021
14 Oct 21
14 Oct 2021 16:18:52:000000
STR_TO_DATE:
SELECT STR_TO_DATE('15:00:00', '%H:%i:%s');
SELECT STR_TO_DATE('2021-10-14 15:00:00', '%Y-%m-%d %H:%i:%s');
结果:
15:00:00
2021-10-14 15:00:00
5. Matters needing attention
STR_TO_DATE
中str的格式需要和format的格式保持一致;例如 str_to_date(‘2021-10-14 15:00:00’,‘%Y-%m-%d %H:%i:%s’),若是前后不一致则会报错。
示例: