当前位置: 代码网 > it编程>数据库>Mysql > MySQL中日期和时间戳转换之字符到DATE和TIMESTAMP的相互转换

MySQL中日期和时间戳转换之字符到DATE和TIMESTAMP的相互转换

2024年12月13日 Mysql 我要评论
在mysql中,经常需要在date、timestamp和字符串之间进行相互转换。以下是一些常见的转换方法:1.字符串到日期/时间类型字符串转date:使用str_to_date()函数将字符串转换为d

在mysql中,经常需要在 datetimestamp 和字符串之间进行相互转换。以下是一些常见的转换方法:

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() 函数可以在 datetimestamp 和字符串之间进行转换。

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com