Time consts in Java?

JavaDateTimeConstants

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

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.

Solution 3 - 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

Solution 4 - Java

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.

Solution 5 - Java

The Java TimeUnit seems to be what you want

Solution 6 - Java

Joda Time also has a DateTimeConstants class with things like MILLIS_PER_SECOND, SECONDS_PER_MINUTE, MILLIS_PER_DAY, etc, etc.

Solution 7 - Java

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

Solution 8 - Java

While TimeUnit discussed in this Answer and Duration discussed in this Answer probably more directly addresses the Question, there are some other handy units-of-time features in Java.

java.time

For units, see the ChronoUnit enum:

  • FOREVER
  • ERAS
  • MILLENNIA
  • CENTURIES
  • DECADES
  • YEARS
  • MONTHS
  • WEEKS
  • DAYS
  • HALF_DAYS
  • HOURS
  • MINUTES
  • SECONDS
  • MILLIS
  • MICROS
  • NANOS

The java.time package has sophisticated enums for DayOfWeek and Month. So rather than pass around a mere number or string, you can pass full-fledged objects such as DayOfWeek.TUESDAY or Month.FEBRUARY.

The java.time framework also includes classes such as MonthDay, YearMonth, and Year. Again, you can pass full-fledged objects rather than mere numbers or strings to make your code more self-documenting, ensure valid values, and provide type-safety.

Converting between TimeUnit and ChronoUnit

We can easily convert between TimeUnit and ChronoUnit. See the new methods added to the older class, TimeUnit.

ThreeTen-Extra project

The ThreeTen-Extra project provides additional classes to work with java.time. These include: DayOfMonth, DayOfYear, AmPm, Quarter, YearQuarter, YearWeek, Days, Weeks, Months, Years, and Interval.

Solution 9 - Java

One more approach with already baked (for multiple call) Duration instances (and 0 math operations):

ChronoUnit.DAYS.getDuration().getSeconds()

Solution 10 - Java

              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().

Solution 11 - Java

I doubt it, because they aren't all constants. The number of milliseconds for a year varies, right?

Solution 12 - Java

If you mean to obtain the values Calendar have all fields related to time management, with some simple reflection you can do

Field[] fields = Calendar.class.getFields();

for (Field f : fields)
{
  String fName = f.toString();
  System.out.println(fName.substring(fName.lastIndexOf('.')+1).replace("_", " ").toLowerCase());
}

this will output:

era
year
month
week of year
week of month
date
day of month
day of year
day of week
day of week in month
am pm
hour
hour of day
minute
second
millisecond
zone offset
dst offset
field count
sunday
monday
tuesday
wednesday
thursday
friday
saturday
january
february
march
april
may
june
july
august
september
october
november
december
undecimber
am
pm
all styles
short
long

from which you can exclude what you don't need.

If you need just constants you have them: Calendar.DAY_OF_MONTH, Calendar.YEAR and so on..

Solution 13 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYossaleView Question on Stackoverflow
Solution 1 - JavatheadamView Answer on Stackoverflow
Solution 2 - JavaMateusz SzulcView Answer on Stackoverflow
Solution 3 - JavaOded BreinerView Answer on Stackoverflow
Solution 4 - JavaBrian AgnewView Answer on Stackoverflow
Solution 5 - JavaMartinView Answer on Stackoverflow
Solution 6 - JavaLindsay ThurmondView Answer on Stackoverflow
Solution 7 - JavaReaz MurshedView Answer on Stackoverflow
Solution 8 - JavaBasil BourqueView Answer on Stackoverflow
Solution 9 - JavaVlad D.View Answer on Stackoverflow
Solution 10 - JavaPindatjuhView Answer on Stackoverflow
Solution 11 - JavaduffymoView Answer on Stackoverflow
Solution 12 - JavaJackView Answer on Stackoverflow
Solution 13 - JavaKarthik RaoView Answer on Stackoverflow