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.
If the constants are to be used as Compile-time constants (for example, as an attribute in an annotation), then Apache DateUtils
will come in handy.
import org.apache.commons.lang.time.DateUtils;
DateUtils.MILLIS_PER_SECOND
DateUtils.MILLIS_PER_MINUTE
DateUtils.MILLIS_PER_HOUR
DateUtils.MILLIS_PER_DAY
These are primitive long constants.
Here's what I use for getting milliseconds.
import javax.management.timer.Timer;
Timer.ONE_HOUR
Timer.ONE_DAY
Timer.ONE_MINUTE
Timer.ONE_SECOND
Timer.ONE_WEEK
60 * 1000 miliseconds in 1 minute
60 seconds in 1 minute
1 minute in 1 minute
1/60 hours in 1 minute
1/(60*24) days in 1 minute
1/(60*24*365) years in 1 minute
1/(60*24*(365 * 4 + 1)) 4 years in 1 minute
* 60 is in 1 hour
* 60 * 24 is in 1 day
* 60 * 24 * 365 is in 1 year
etc.
Create them yourself, I guess, is the easiest. You can use the Date
and Calendar
classes to perform calculations with time and dates. Use the long
data type to work with large numbers, such as miliseconds from 1 Januari 1970 UTC, System.currentTimeMillis()
.
Joda-Time contains classes such as Days, which contain methods such as toStandardSeconds(). So you can write:
int seconds = Days.ONE.toStandardSeconds();
although it seems a little verbose, and perhaps is only useful for more complex scenarios such as leap years etc.
If on android, I suggest:
android.text.format.DateUtils
DateUtils.SECOND_IN_MILLIS
DateUtils.MINUTE_IN_MILLIS
DateUtils.HOUR_IN_MILLIS
DateUtils.DAY_IN_MILLIS
DateUtils.WEEK_IN_MILLIS
DateUtils.YEAR_IN_MILLIS
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);