简体   繁体   English

在Java应用程序中管理时间的最佳方法是什么?

[英]What is the best way to manage Time in a Java application?

So I'm using hibernate and working with an application that manages time. 因此,我正在使用休眠方式,并与一个用于管理时间的应用程序一起使用。 What is the best way to deal with times in a 24 hour clock? 在24小时制中处理时间的最佳方法是什么?

I do not need to worry about TimeZone issues at the beginning of this application but it would be best to ensure that this functionality is built in at the beginning. 我不需要担心此应用程序开头的TimeZone问题,但是最好确保在开始时就内置了此功能。

I'm using hibernate as well, just as an fyi 我也使用冬眠,就像飞

Store them as long ts = System.currentTimeMillis(). 将它们存储为长ts = System.currentTimeMillis()。 That format is actually TimeZone-safe as it return time in UTC. 该格式实际上是TimeZone安全的,因为它以UTC返回时间。

If you only need time part, well, I'm not aware of built-in type in Hib, but writing your own type Time24 is trivial -- just implement either org.hibernate.UserType or org.hibernate.CompositeUserType (load=nullSafeGet and store=nullSafeSet methods in them). 好吧,如果您只需要时间部分,我不知道Hib中的内置类型,但是编写自己的类型Time24是微不足道的-只需实现org.hibernate.UserType或org.hibernate.CompositeUserType(load = nullSafeGet并在其中存储= nullSafeSet方法)。

See http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types-custom 参见http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-types-custom

But I'd still save absolute time anyway. 但是我仍然会节省绝对的时间。 May help in future. 将来可能会有所帮助。

PS That's all presuming storing Date is out of question for some reason. PS这就是所有假定存储Date出于某种原因而毫无疑问的方法。 TimeZone in Date sometimes gets in the way, really. 实际上,日期中的TimeZone有时会妨碍您。 ;) ;)

I would suggest you look into using Joda, http://joda-time.sourceforge.net/ , which offers much more intuitive and controllable time handling functionality than the core Date and Calendar implementations. 我建议您考虑使用Joda, http://joda-time.sourceforge.net/ ,它提供了比核心Date和Calendar实现更加直观和可控制的时间处理功能。 JSR 310 is actually a proposition to include a new time API into java 7 that will be based largely on Joda. JSR 310实际上是在Java 7中包括新时间API的主张,它将主要基于Joda。 Joda also offers both timezone dependent Time handling and timezone independent time handling which eases difficulties when dealing with intervals. Joda还提供了与时区相关的时间处理和与时区无关的时间处理,从而减轻了处理间隔时的困难。

使用java.util.Date有什么问题吗?

java.util.Date should be used; 应该使用java.util.Date ; not a long (and definitely not a Calendar ). 不长(而且绝对不是Calendar )。

If you are using annotations be sure to use @Temporal 如果您使用注释,请确保使用@Temporal

I also found another library recently that seems to be a response to JODA. 我最近还发现了另一个图书馆,它似乎是对JODA的回应。 http://www.date4j.net/ http://www.date4j.net/

The advantages are listed on the project home page. 优点列在项目主页上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM