Time consts in Java?

前端 未结 13 609
遇见更好的自我
遇见更好的自我 2020-12-23 15:45

Is there a Java package with all the annoying time constants like milliseconds/seconds/minutes in a minute/hour/day/year? I\'d hate to duplicate something like that.

13条回答
  •  旧时难觅i
    2020-12-23 16:30

    I would go with java TimeUnit if you are not including joda-time in your project already. You don't need to include an external lib and it is fairly straightforward.

    Whenever you need those "annoying constants" you usually need them to mutliply some number for cross-unit conversion. Instead you can use TimeUnit to simply convert the values without explicit multiplication.

    This:

    long millis = hours * MINUTES_IN_HOUR * SECONDS_IN_MINUTE * MILLIS_IN_SECOND;
    

    becomes this:

    long millis = TimeUnit.HOURS.toMillis(hours);
    

    If you expose a method that accepts some value in, say, millis and then need to convert it, it is better to follow what java concurrency API does:

    public void yourFancyMethod(long somePeriod, TimeUnit unit) {
        int iNeedSeconds = unit.toSeconds(somePeriod);
    }
    

    If you really need the constants very badly you can still get i.e. seconds in an hour by calling:

    int secondsInHour = TimeUnit.HOURS.toSeconds(1);
    

提交回复
热议问题