java日期和mysql 日期

Java(1.6) 中能保存时间日期类型的类主要有

java.util.Date

java.util.Calendar

java.sql.Date

java.sql.Time

java.sql.Timestamp

以前从mysql中查询出来的时间日期类型,都放在java.util.Date类型里面了。这样带来一系列的问题,首先这个类提供的时间操作函数太少,一般都需要转换成java.util.Calendar再去操作;其次即使使用了java.util.Calendar,也不是很方便,一个很简单的想法,需要写很多代码才能实现;java.util.Date的数据内容为xxxx-xx-xx xx:xx:xx,有时候不需要时间,只需要日期。从数据库中取值出来的日期类型放到这个类中的时候,会在时间位自动补上当前时间。这使得本来两个日期在数据库中是相等的,取出来放到这个类得时候就不再相等了,需要去考虑时间上的误差,很是头疼。

java提供与mysql方便交互的三种数据类型

java.sql.Date

java.sql.Time

java.sql.Timestamp

它们都是继承java.util.Date,算是对该类的精简,很适合跟数据库交互。

===========java注入数据库==========

java类型 mysql类型 成功与否

date date yes

date time no

date timestamp no

date datetime no

time date no

time time yes

time timestamp no

time datetime no

timestamp date yes

timestamp time yes

timestamp timestamp yes

timestamp datetime yes

==========end java注入数据库========

总规律,如果A完全包含B,则A可以向B注入数据,否则报错

==========从数据库提取到java ==========

mysql类型 java类型 成与否

date date yes

date time yes --------------缺少的部分使用历元

date timestamp yes --------------缺少的部分使用历元

time date yes --------------缺少的部分使用历元

time time yes

time timestamp yes --------------缺少的部分使用历元

timestamp date yes

timestamp time yes

timestamp timestamp yes

datetime date yes

datetime time yes

datetime timestamp yes

==========end 从数据库提取到java=======

不会出错,缺少的部分使用历元,而不是当前日期时间

null to db(null) =====> 也是null

null to db(not null)=======> 数据库报错

db(null) to java==========> 如果单字段出来,则整个entity都是null,如果带着其他不是null的字段出来,则可以实例化entity,本身字段依然是null

db(not null) to java==========> 如果包含日期,则报错,否则为000

最优解决方案,定义成可以为null

java.sql时间系统的运算系列

after,before

compareTo原小于参数返回<0,等于返回=0,大于返回>0

优点:于数据库同类型,可以方便传输(无论是从DB到src还是反方向),方便比较大小

缺点:缺少运算单元,不适合时间跳跃的运算和间隔的运算

总结:calendar具有强大的跳跃运算和间隔运算能力,在需要的时候,可以将sql系列的时间转成calendar。

先设置calendar为历元,然后从sql系列时间中转换,最后再转回sql系列时间。

calendar只用于时间有跳跃的转换,对比运算统一使用sql系统,这样代码将更清晰

date 和 calendar怎么初始化为格林威治时间

new date(0)

calendar.setTimeInMillis(0)

sql系列时间

static valueOf

new XX(0)获得历元

new XX(year+1900, month+1,day,hour,minute,second,nano)已过时,创建也没错

toString或者SimpleDateFormat