在mysql中,经常需要在 date、timestamp 和字符串之间进行相互转换。以下是一些常见的转换方法:
1.字符串到日期/时间类型
字符串转 date:
使用 str_to_date() 函数将字符串转换为 date 类型。你需要提供字符串的格式。
select str_to_date('2024-08-24', '%y-%m-%d') as my_date;
字符串转 timestamp:
同样使用 str_to_date() 函数,但格式要包括时间部分。
select str_to_date('2024-08-24 14:35:00', '%y-%m-%d %h:%i:%s') as my_timestamp;
2.日期/时间类型到字符串
date 转字符串:
使用 date_format() 函数将 date 转换为指定格式的字符串。
select date_format(now(), '%y-%m-%d') as date_str;
timestamp 转字符串:
使用 date_format() 函数将 timestamp 转换为指定格式的字符串。
select date_format(now(), '%y-%m-%d %h:%i:%s') as timestamp_str;
3.日期类型和时间戳类型之间的转换
date 转 timestamp:
date 类型只有日期部分,没有时间部分,mysql 在转换时会默认将时间部分设置为 00:00:00。
select cast('2024-08-24' as datetime) as date_to_timestamp;
timestamp 转 date:
使用 date() 函数从 timestamp 中提取日期部分。
select date(now()) as timestamp_to_date;
4.unix_timestamp和date/timestamp的相互转换
unix_timestamp 转 timestamp:
使用 from_unixtime() 函数将 unix_timestamp 转换为 timestamp。
-- 将unix时间戳转为时间戳 select from_unixtime(unix_timestamp()) as unix_to_timestamp; -- unix时间戳转时间戳 (如果是13位需要除1000) select from_unixtime(1692874200) as unix_to_timestamp;
timestamp 转 unix_timestamp:
使用 unix_timestamp() 函数将 timestamp 转换为 unix_timestamp。
-- 将时间戳转换为unix时间戳 select unix_timestamp(now()) as timestamp_to_unix;
5.直接通过类型转换函数
cast 和 convert 函数:
使用 cast() 或 convert() 函数可以在 date、timestamp 和字符串之间进行转换。
select cast('2024-08-24 14:35:00' as date) as cast_to_date;
select convert(now(), char) as convert_to_string;
6. 字符串到日期或时间戳,带时区的转换
convert_tz: 将时间戳从一个时区转换到另一个时区。
– 将utc时间戳转换为东八区时间
select convert_tz(‘2024-08-24 06:00:00’, ‘+00:00’, ‘+08:00’);
7. 字符串直接转换为时间戳
如果字符串格式与时间戳的默认格式一致,可以直接进行转换,这会自动将字符串转换为时间戳。注意这种方法仅适用于字符串格式精确匹配默认的datetime格式。
select ‘2024-08-24 14:30:00’ + 0 as timestamp_value;
常用的格式化符号:
%y年(四位)%m月(两位)%d日(两位)%h小时(24小时制)%i分钟%s秒
以上就是mysql实现字符到date和timestamp的相互转换的详细内容,更多关于mysql字符到date和timestamp转换的资料请关注代码网其它相关文章!
发表评论