Time consts in Java?
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);
Java 8 / java.time solution
As an alternative to TimeUnit
, you might for some reason prefer the Duration class from java.time package:
Duration.ofDays(1).getSeconds() // returns 86400;
Duration.ofMinutes(1).getSeconds(); // 60
Duration.ofHours(1).toMinutes(); // also 60
//etc.
Additionally, if you would go deeper and have analyzed how Duration.ofDays(..) method works, you would see the following code:
return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0);
where SECONDS_PER_DAY
is a package protected static constant from LocalTime class.
/**
* Seconds per day.
*/
static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;
//there are also many others, like HOURS_PER_DAY, MINUTES_PER_HOUR, etc.
I think it is safe to assume that if there would be any package, which would defined "all the annoying time constants like miliseconds/seconds/minutes" as you call them, I believe Java SDK Developers would have use them.
Why are this LocalTime
constants package protected and not public that is a good question, I believe there is a reason for that. For now it looks like you really have to copy them and maintain on your own.