时间:2021-07-01 10:21:17 帮助过:27人阅读
二、数值型与日期和时间型的转化
### 数值型转为日期和时间型: 20190903 --> 日期2019-09-03 select cast(20190903 as date); 815 --> 时间00:08:15 select cast(815 as time); 0200815002356 --> 时间戳2020-08-15 00:23:56 select cast(20200815002356 as datetime); ##把Unix时间戳转为日期 1628434346325 --> 2021-08-08 22:52:26 select from_unixtime(1628434346325/1000, ‘%Y-%m-%d %H:%i:%s‘); ### 日期时间型转为数值型: 如:2019-09-03 –> 20190903 select cast(current_date() as signed); 如:14:04:10 –> 140410 select cast(current_time() as signed); 如:2019-09-03 14:04:10 --> 20190903140410 select cast(now() as signed); 如:如:2019-09-03 –> 2019 select year(current_date()); 如:14:04:10 –> 10 select second(current_time); ##把日期类型转为Unix时间戳 select unix_timestamp(‘2019-09-03 11:47:30‘);
三、字符型与日期和时间型的转化
### 字符型转换为日期时间型: ‘20190903’ --> 日期2019-09-03 select cast(‘20190903‘ as date); ‘2019-09-03‘ --> 日期2019-09-03 select cast(‘2019-09-03‘ as date); ‘2109/09/03’ --> 日期2019-09-03 select cast(‘2019/09/03‘ as date); ‘2019#09#03’ --> 日期2019-09-03 select cast(‘2019#09#03‘ as date); ‘00:08:15‘ --> 时间00:08:15 select cast(‘00:08:15‘ as time); ‘20210808225226‘ --> 时间戳2020-08-15 00:08:15 select CAST(‘20210808225226‘ AS DATETIME); ‘2021-08-08 22:52:26‘ --> 时间戳2021-08-08 22:52:26 select cast(‘2021-08-08 22:52:26‘ as datetime); ### 日期时间型转为字符型: 如:日期2019-09-03 –> ‘20190903‘ select DATE_FORMAT(CURRENT_DATE(),‘%Y%m%d‘) 如:日期2019-09-03 --> ‘2019-09-03‘ select CAST(CURRENT_DATE() AS DATE); select DATE_FORMAT(CURRENT_DATE(),‘%Y-%m-%d‘); 如:日期2020-08-15‘ --> ‘2020-08‘ select DATE_FORMAT(CURRENT_DATE(),‘%Y-%m‘); 时间00:08:15 --> ‘00:08:15‘ select DATE_FORMAT(NOW(),‘%H:%i:%s‘); select CAST(CURRENT_TIME() AS CHAR); 时间戳2020-08-15 00:08:15 –> ‘20210808225226‘ select DATE_FORMAT(NOW(),‘%Y%m%d%H%i%s‘) 时间戳2021-08-08 22:52:26 --> ‘2021-08-08 22:52:26‘ select CAST(NOW() AS CHAR); select DATE_FORMAT(NOW(),‘%Y-%m-%d %H:%i:%s‘); 日期2020-08-15 --> Thursday select DAYNAME(CURRENT_DATE()); 日期2020-08-15 --> August select MONTHNAME(CURRENT_DATE());
SQL进阶-数据类型转换
标签:tps ascii sql ack ast signed idt char current