时间在 Java 中占多数?

有没有一个 Java 包包含所有烦人的时间常量,比如 毫秒/秒/分钟/分钟/小时/天/年? 我讨厌重复这样的东西。

59815 次浏览
              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 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..

The Java TimeUnit seems to be what you want

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

Joda Time also has a DateTimeConstants class with things like MILLIS_PER_SECOND, SECONDS_PER_MINUTE, MILLIS_PER_DAY, etc, 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

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 DayOfYear1 project provides additional classes to work with java.time. These include: DayOfMonth, DayOfYear, AmPm, Quarter, YearQuarter, YearWeek, Days, Weeks, Months, Years, and DayOfYear0.

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.

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

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

ChronoUnit.DAYS.getDuration().getSeconds()

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.