简体   繁体   中英

How to represent in a modular java project date and time attributes across classes? (mongo used as DB)

We are looking for the best way to represent date and time attributes in our classes, that are being persisted in a mongoDB.

Mongo uses internally a Date() from javascript, so we can use Java new Date(long millis) constructor which is not deprecated to create date instances and use it to getTime() in millis back again. We wanted to use Date since we could later use $date mongo operations on it. That would not be possible with simple long millis.

However, we are thinking of the best way how to represent time in our project, since we will be probably working with things like daylight saving time, different UTC zones etc.

Our approach which we would like to check with you if it is safe and efficient would be:

public class SomeClass{
    private Date someDate;

    public Calendar getDate(){
        return new GregorianCalendar().setTimeInMillis(someDate.getTime());
    }
} 

Calendar should be safe to use in respect to the UTC zones and saving times and for comparison operations etc., AFAIK.

We were also considering using Java 8 Time, but we are not sure of the consequences of using new Java - if we might not end up in some problems.

  • So is this approach good?
  • Should we switch to Java 8 and use Time, because it is safe to do so?
  • Is Date really safe to be used, if it is only used for storing the millis and getting the millis back from it? Won't we stumble upon some issues like unexpectable +/- 1 hour differences in the date/time value?
  • Can you think of a better approach to represent date/time in our project? What is a standard approach to this issue?

You can store a Date directly. Times are stored internally as UTC so daylight savings shouldn't be a problem for you. The driver doesn't currently support Java 8 (or joda time) date/time types but there are links around showing how that's done. If you're using morphia, you can see what a converter looks like for Java 8's LocalDateTime here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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