最好的方法是尽可能避免使用unix_timestamp/from_unixtime,而在您的情况下这是可能的。date()
可以被移除,yyyy-MM-dd
格式的字符串与date
类型兼容:
select date(concat_ws('-',substr(ts,1,4),substr(ts,5,2),substr(ts,7,2)))
from
(
select '20210412070422' as ts
)s
结果:
2021-04-12
使用regexp_replace的另一种高效方法:
select regexp_replace(ts,'^(\\d{4})(\\d{2})(\\d{2}).*','$1-$2-$3')
如果您更喜欢使用unix_timestamp/from_unixtime
select date(from_unixtime(unix_timestamp(ts, 'yyyyMMddHHmmss')))
from
(
select '20210412070422' as ts
)s
但是这种方法更加复杂,速度较慢(涉及SimpleDateFormat类),且容易出错,因为如果数据不完全符合预期格式,例如 '202104120700',则无法正常工作。
当然,您可以通过截取所需长度的子字符串并使用yyyyMMdd模板来使其更加可靠:
select date(from_unixtime(unix_timestamp(substr(ts,1,8), 'yyyyMMdd')))
from
(
select '20210412070422' as ts
)s
这让它变得更加复杂。
只有在像“2021Apr12blabla”这样的数据格式无法使用简单的substr或regexp_replace时,才使用unix_timestamp/from_unixtime。