时间, 字符串, 时间戳之间的互相转换很常用, 但是几乎每次使用时候都喜欢去搜索一下用法; 本文整理一下三者之间的 转换 (即: date 转字符串, date 转时间戳, 字符串转 date, 字符串转时间戳, 时间戳转 date, 时间戳转字符串) 用法, 方便日后学习和查阅;
涉及的函数
https://wuzhuti.cn/tag/date_format/ (date, format) 函数, MySQL 日期格式化函数 date_format() https://wuzhuti.cn/2367.html
https://wuzhuti.cn/tag/unix_timestamp/ () 函数
https://wuzhuti.cn/tag/str_to_date/ (str, format) 函数
https://wuzhuti.cn/tag/from_unixtime/ (unix_timestamp, format) 函数, MySQL 时间戳格式化函数 from_unixtime https://wuzhuti.cn/2538.html
时间转字符串
- select date_format(now(), '%Y-%m-%d');
- # 结果: 2017-01-05
时间转时间戳
- select unix_timestamp(now());
- # 结果: 1452001082
字符串转时间
- select str_to_date('2016-01-02', '%Y-%m-%d %H');
- # 结果: 2017-01-02 00:00:00
- select str_to_date('20181010000000','%Y%m%d%H%i%s');
- # 结果: 2018-10-10 00:00:00
- # 同表, 把一个字段值格式成日期格式赋值给另一个字段
UPDATE 表名 set 字段名 = STR_TO_DATE(字段名,'%Y%m%d%H%i%s')
字符串转时间戳
- select unix_timestamp('2016-01-02');
- # 结果: 1451664000
时间戳转时间
- select from_unixtime(1451997924);
- # 结果: 2017-01-05 20:45:24
时间戳转字符串
- select from_unixtime(1451997924,'%Y-%d');
- // 结果: 2017-01-05 20:45:24
附表
MySQL 日期格式化 (format) 取值范围.
值 | 含义 | |
---|---|---|
秒 | %S、%s | 两位数字形式的秒( 00,01, ..., 59) |
分 | %I、%i | 两位数字形式的分( 00,01, ..., 59) |
小时 & nbsp; | %H | 24 小时制,两位数形式小时(00,01, ...,23) |
%h | 12 小时制,两位数形式小时(00,01, ...,12) | |
%k | 24 小时制,数形式小时(0,1, ...,23) | |
%l | 12 小时制,数形式小时(0,1, ...,12) | |
%T | 24 小时制,时间形式(HH:mm:ss) | |
%r | 12 小时制,时间形式(hh:mm:ss AM 或 PM) | |
%p | AM 上午或 PM 下午 & nbsp; | |
周 & nbsp; | %W | 一周中每一天的名称(Sunday,Monday, ...,Saturday) |
%a | 一周中每一天名称的缩写(Sun,Mon, ...,Sat) | |
%w | 以数字形式标识周(0=Sunday,1=Monday, ...,6=Saturday) | |
%U | 数字表示周数,星期天为周中第一天 | |
%u | 数字表示周数,星期一为周中第一天 | |
天 | %d | 两位数字表示月中天数(01,02, ...,31) |
%e | 数字表示月中天数(1,2, ...,31) | |
%D | 英文后缀表示月中天数(1st,2nd,3rd ...) | |
%j | 以三位数字表示年中天数(001,002, ...,366) | |
月 | %M | 英文月名(January,February, ...,December) |
%b | 英文缩写月名(Jan,Feb, ...,Dec) | |
%m | 两位数字表示月份(01,02, ...,12) | |
%c | 数字表示月份(1,2, ...,12) | |
年 | %Y | 四位数字表示的年份(2015,2016...) |
%y | 两位数字表示的年份(15,16...) | |
文字输出 & nbsp; | % 文字 & nbsp; | 直接输出文字内容 |
来源: http://www.bubuko.com/infodetail-3090889.html