zoukankan      html  css  js  c++  java
  • mysql 日期时间类型

    datetime timestamp year date time

    drop table test;
    create table test (dt datetime, ts timestamp, y year, d date, t time);
    insert into test values(now(),now(),now(),now(),now());
    select * from test;
    2018-07-14 21:55:13 , 2018-07-14 21:55:13, 2018, 2018-07-14, 21:55:13


    timestamp

    1、timestamp 值返回后显示为“YYYY-MM-DD HH:MM:SS”格式的字符串,显示宽度固定为 19 个字符。如果想要获得数字值,应在 timestamp 列添加+0。
    select ts+0 from test; // 20180714215513

    2、系统给 timestamp 自动创建默认值 current_timestamp
    drop table test;
    create table test(id timestamp);
    insert into test values(null);
    select * from test; // 2007-07-04 16:37:24

    注意,MySQL只给表中的第一个timestamp字段设置默认值为系统日期,如果有第二个timestamp类型,则默认值设置为0值
    alter table test add id2 timestamp;
    insert into test values(null, null);
    select * from test; // 2018-07-14 21:04:15 0000-00-00 00:00:00

    可以修改id2的默认值为其他常量日期,但是不能再修改为current_timestmap,因为MySQL规定timestamp类型字段只能有一列的默认值为current_timestmap,如果强制修改,系统会报错。
    drop table test;
    create table test(id timestamp, id2 timestamp);
    alter table test alter column id2 set default current_timestamp; // 报错
    alter table test alter column id2 set default 20180714215513;

    3、timestamp还有一个重要特点,就是和时区相关。当插入日期时,会先转换为本地时区后存放;而从数据库里面取出时,也同样需要将日期转换为本地时区后显示。这样,两个不同时区的用户看到的同一个日期可能是不一样的。
    drop table test;
    create table test (
    `id1` timestamp not null default current_timestamp,
    `id2` datetime default null
    )
    show variables like 'time_zone'; // SYSTEM 查看当前时区,我们在中国,这里的“SYSTEM”实际是东八区(+8:00)
    insert into t8 values(now(), now());
    select * from t8;
    | 2007-09-25 17:26:50 | 2007-09-25 17:26:50 |
    修改时区为东九区: set time_zone='+9:00';
    select * from t8;
    | 2007-09-25 18:26:50 | 2007-09-25 17:26:50 |


     timestamp和datetime的表示方法非常类似,区别主要有以下几点。

    1、timestamp支持的时间范围较小,其取值范围从19700101080001到2038年的某个时间,而datetime是从1000-01-01 00:00:00到9999-12-31 23:59:59,范围更大。
    2、表中的第一个timestamp列自动设置为系统时间。如果在一个timestamp列中插入null,则该列值将自动设置为当前的日期和时间。在插入或更新一行但不明确给timestamp列赋值时也会自动设置该列的值为当前的日期和时间,当插入的值超出取值范围时,mysql认为该值溢出,使用“0000-00-00 00:00:00”进行填补。
    3、timestamp的插入和查询都受当地时区的影响,更能反应出实际的日期。而datetime则只能反应出插入时当地的时区,其他时区的人查看数据必然会有误差的。

  • 相关阅读:
    SpringMVC框架(4)--异常处理
    SpringMVC框架(3)--文件上传与SpringMVC拦截器
    SpringMVC框架(1)--基础入门
    Spring框架(6)--JDBCTemplate的使用和Spring的事务控制
    Spring框架(5)--AOP相关内容
    Spring框架(4)--Spring注解开发
    Spring框架(3)--Spring配置数据源
    Spring框架(2)--依赖注入
    考试倒计时
    递归列表
  • 原文地址:https://www.cnblogs.com/Mike_Chang/p/9311117.html
Copyright © 2011-2022 走看看