你在java模型中如何表示出生日期? [英] How would you represent date of birth in your java model?

查看:643
本文介绍了你在java模型中如何表示出生日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

等待,不要急于回答java.util.Date,请考虑以下情况。

And wait, don't rush to answer "java.util.Date", consider the following scenario.

拥有2个字段的Person对象为birthday和nextMeeting都是java.util.Date。
现在生日以数据库形式存储为日期类型列(没有时间),例如。 01-10-1979,nextMeeting作为例如日期时间类型。 01-10-2010 20:00:00。

Person object having 2 fields: "birthday" and "nextMeeting" both java.util.Date. Now birthday stored in database as date type column (no time) for eg. 01-10-1979, and nextMeeting as datetime type for ex. 01-10-2010 20:00:00.

您从db中提取生日将通过JDBC自动设置为午夜。
现在,您需要使用RMI或任何技术将此对象发送到其他JVM。

You pull it from db, "birthday" will be auto set to midnight by JDBC. Now you need to send this object to other JVM using lets say RMI or whatever technology.

另一方面,JVM具有来自始发JVM的时区-1h。这是问题开始的地方。
nextMeeting成为01-10-2010 19:00:00,从用户的角度来看绝对是精细和正确的等等。

On the other end JVM has timezone -1h from originating JVM. This is where problem starts. nextMeeting become 01-10-2010 19:00:00 which is absolutely FINE and CORRECT from user perspective etc...

生日成为30-09 -1979 23:00:00这将在9月30日由用户代表,这真的不是我们想要的,因为明显的生日是静态的,不依赖于时区。

BUT birthday become 30-09-1979 23:00:00 which will be represented to user as 30th of September, which is really not what we want, cause obviously birthday is something static and NOT dependent on timezones.

所以db中的列类型正确选择(日期)。这种类型的列通常表示为java.util.Date。但是在我们的例子中,使用java类型是错误的。

So column type in db chosen correctly (date). This type of column usually represented as java.util.Date. But in our case it is wrong java type to use.

那么你怎么代表一个生日?考虑你需要在一个UI上操作这个对象,就像在datepicker组件等中一样。

So how would you represent a birthday? Consider that you need to manipulate this object on a UI like in a datepicker component etc...

推荐答案

使用 LocalDate from JodaTime ,只存储生日的日期,而不是时间。

Use LocalDate from JodaTime and only store the date for the birthday, not the time.

这篇关于你在java模型中如何表示出生日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆