在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相互转换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论