一、unix_timestamp函数用法
1、UNIX_TIMESTAMP() :若无参数调用,则返回一个 Unix timestamp ('1970-01-01 00:00:00' GMT 之后的秒数) 作为无符号整数,得到当前时间戳
2、UNIX_TIMESTAMP(date) :若用date 来调用 UNIX_TIMESTAMP(),它会将参数值以'1970-01-01 00:00:00' GMT后的秒数的形式返回。date 可以是一个 DATE 字符串、一个 DATETIME字符串、一个 TIMESTAMP或一个当地时间的YYMMDD 或YYYMMDD格式的数字。
采用yyyyMMdd或yyyyMM、yyyy-MM-dd数字格式时候,需要在UNIX_TIMESTAMP()内标明格式,比如UNIX_TIMESTAMP(2022023,'yyyyMMdd')
例如:
mysql> SELECT UNIX_TIMESTAMP() ; (执行时的时间:2009-08-06 10:10:40)
->1249524739
mysql> SELECT UNIX_TIMESTAMP('2009-08-06') ;
->1249488000
如何将’2017/05/21’,转换成’2017-05-21’
方法1:
select from_unixtime( unix_timestamp('2017/05/21','yyyy/MM/dd'),'yyyy-MM-dd') data_dt;
2017-05-21
1
2
方法2:
select date_format (regexp_replace('2017/05/21','/','-'),'yyyy-MM-dd') data_dt;
2017-05-21
二、from_unixtime函数用法
语法:from_unixtime(t1,’yyyy-MM-dd HH:mm:ss’)
其中t1是10位的时间戳值,即1970-1-1至今的秒,而13位的所谓毫秒的是不可以的。
对于13位时间戳,需要截取,然后转换成bigint类型,因为from_unixtime类第一个参数只接受bigint类型。例如:
select from_unixtime(cast(substring(tistmp,1,10) as bigint),’yyyy-MM-dd HH’) tim ,count(*) cn from ttengine_hour_data where …
他们两个可以结合使用from_unixtime(unix_timestamp(date_created),'yyyy-MM-dd HH:mm:ss')来规范时间的格式。
to_date 和add_months
举例:
select
date_f, --19801217
concat(substring(date_f,1,4),'-',substring(date_f,5,2),'-',substring(date_f,7,2)),
unix_timestamp(date_f,'yyyyMMdd'),
to_date(from_unixtime(unix_timestamp(date_f,'yyyyMMdd'))),
add_months(concat(substring(date_f,1,4),'-',substring(date_f,5,2),'-',substring(date_f,7,2)),-24)
--19801217,1980-12-17,345859200,1980-12-17,1978-12-17
select substring(`current_timestamp`(),1,7),
to_date(`current_timestamp`()),
add_months(to_date(`current_timestamp`()),-24),
unix_timestamp(add_months(to_date(`current_timestamp`()),-24),'yyyy-MM-dd');
--2022-10,2022-10-23,2020-10-23,1603411200
本文详细介绍了MySQL中UNIX_TIMESTAMP和FROM_UNIXTIME函数的用法,包括如何转换日期格式,以及如何结合使用来规范化时间格式。示例展示了如何将不同格式的日期转换为Unix时间戳,以及如何将Unix时间戳转换回日期,并进行月份的加减操作。此外,还提到了to_date和add_months函数的应用。
4174





