美文网首页
Mysql 日期,时间戳,字符串相互转换

Mysql 日期,时间戳,字符串相互转换

作者: 沧海2122537190 | 来源:发表于2020-04-08 18:56 被阅读0次

    一、函数介绍

    1、date_format(date, format)

    将date按照formatj进行格式化,
    date 参数是合法的日期,
    format 规定日期/时间的输出格式。

    2、str_to_date(str, format)

    将字符串转换为日期类型,输出结果为DATETIME类型的值,
    str参数为目标字符串,
    format 规定日期/时间的输出格式。
    str中日期的格式要与format格式相同,否则结果为“NULL”。

    3、unix_timestamp(date)

    将date中的时间转换为时间戳,
    date省略时,返回当前时间的时间戳。

    4、from_unixtime(unix_timestamp, format)

    将时间戳unix_timestamp转换为format中指定格式
    unix_timestamp为目标时间戳
    format 规定日期/时间的输出格式
    format 为空时,默认为形同'%Y-%m-%d %h:%i:%s.%f'的格式

    format可以使用的格式

    格式 描述 格式 描述 格式 描述
    一、 常用参数
    %Y 年,4 位 %y 年,2 位 %M 月名(英文)
    %m 月,数值(00-12) %D 带有英文后缀的月中的天 %d 月的天,数值(00-31)
    %e 月的天,数值(0-31) %H 小时(00-23) %k 小时 (0-23)
    %h 小时 (01-12) %I 小时 (01-12) %i 分钟,数值(00-59)
    %S 秒(00-59) %s 秒(00-59)
    二、 其余参数
    %a 缩写星期名 %b 缩写月名 %c 月,数值
    %f 微秒 %j 年的天(001-366) %p AM 或 PM
    %r 时间,12-小时(hh:mm:ss AM 或 PM) %T 时间, 24-小时 (hh:mm:ss) %U 周 (00-53) 星期日是一周的第一天
    %u 周 (00-53) 星期一是一周的第一天 %V 周 (01-53) 星期日是一周的第一天,与 %X 使用 %v 周 (01-53) 星期一是一周的第一天,与 %x 使用
    %W 星期名 %w 周的天 (0=星期日, 6=星期六) %X 年,其中的星期日是周的第一天,4 位,与 %V 使用
    %x 年,其中的星期一是周的第一天,4 位,与 %v 使用

    二、实例

    1、date_format(date, format)
    select date_format(now(),'%Y-%m-%d')as a,#now()为获取当前日期和时间
    date_format('2020-04-06','%Y-%m-%d')as b,
    date_format('20200406','%Y-%m-%d') as c,
    date_format('2020/04/06','%Y-%m-%d')as d,
    date_format('2026','%Y-%m-%d')as e;#非日期格式
    
    2、str_to_date(str, format)
    select str_to_date('2020-04-06','%Y-%m-%d')as a,
    str_to_date('2020-04-06 10:20:30','%Y-%m-%d')as b,
    str_to_date('2020-4-6','%Y-%m-%d')as c,
    str_to_date('2020/04/06','%Y/%m/%d')as d,
    str_to_date('20200406','%Y%m%d')as e;
    
    3、unix_timestamp()
    select unix_timestamp()as a ,
    unix_timestamp(now())as  b,
    unix_timestamp('2020-04-08')as c,
    unix_timestamp('2020/04/08')as d,
    unix_timestamp('20200408')as e;
    
    4、from_unixtime(unix_timestamp, format)
    select from_unixtime('1586342435')as a ,
    from_unixtime('1586342435','%Y-%m-%d')as  b,
    from_unixtime('15863424351','%Y-%m-%d')as c,#时间戳错误
    from_unixtime('1586342435','%Y-%m-%d %h:%i:%s.%f')as d;
    

    相关文章

      网友评论

          本文标题:Mysql 日期,时间戳,字符串相互转换

          本文链接:https://www.haomeiwen.com/subject/ygqbphtx.html