java时间的数据类型,最适合存储日期和时间的SQL和Java数据类型

本文解答了如何在MySQL中使用DATETIME类型存储和处理'yyyy.MM.ddhh:mm:ss'格式的日期时间,以及如何在Java中通过JDBC转换。介绍了String到Date再到Timestamp的转换过程,并更新了Java 8后的简化方法。
摘要由CSDN通过智能技术生成

Apologies in advance for the somewhat broad question.

What are the most appropriate MySQL and Java data types for handling date and times with the following format: yyyy.MM.dd hh:mm:ss

I need to be able to convert a String representation of the date & time into the given Date Format as well as then store that date&time in the database. I then need to do the reverse and convert the MySQL date & time into the corresponding Java representation

I have read a lot of questions about Date, DateTime, ZonedDateTime but none of these seem to work at all well.

Thanks.

解决方案

What are the most appropriate MySQL and Java data types for handling date and times with the following format: yyyy.MM.dd hh:mm:ss

The most appropriate MySQL type is DATETIME. See Should I use field 'datetime' or 'timestamp'?.

The corresponding Java type to use in your persistence layer (jdbc type) is java.sql.Timestamp. See Java, JDBC and MySQL Types.

I need to be able to convert a String representation of the date & time into the given Date Format as well as then store that date&time in the database.

The correct transformation is: java.lang.String -> java.util.Date -> java.sql.Timestamp.

java.lang.String -> java.util.Date:

Date javaDatetime = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss").parse(stringDatetime);

java.util.Date -> java.sql.Timestamp:

Timestamp jdbcDatetime = new Timestamp(javaDatetime.getTime());

I then need to do the reverse and convert the MySQL date & time into the corresponding Java representation

Do the reverse path:

java.sql.Timestamp -> java.util.Date:

Date javaDatetime = new java.util.Date(jdbcDatetime.getTime());

java.lang.Date -> java.util.String:

String stringDatetime = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss").format(javaDatetime);

I've been concise. You have to pay attention about the use of SimpleDateFormat (e.g. cache an instance which has been initialized with applyPattern and setLenient).

Update for Java 8

Some enhancements have been done on jdbc types (see JDBC 4.2) that simplify conversions. For the case illustrated above you can use toLocalDateTime and valueOf to convert from java.sql.Timestamp to the new java.time.LocalDateTime and back.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值