Java 中的时间常数?

发布于 2024-08-24 16:57:44 字数 65 浏览 3 评论 0原文

是否有一个 Java 包包含所有烦人的时间常数,例如 一分钟/小时/天/年中的毫秒/秒/分钟?我不想重复这样的事情。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

失去的东西太少 2024-08-31 16:57:44

我会选择 java TimeUnit 如果您尚未将 joda-time 包含在您的项目中。您不需要包含外部库,而且它相当简单。

每当您需要这些“烦人的常量”时,您通常需要它们将一些数字相乘以进行跨单位转换。相反,您可以使用 TimeUnit 来简单地转换值,而无需显式乘法。

这:

long millis = hours * MINUTES_IN_HOUR * SECONDS_IN_MINUTE * MILLIS_IN_SECOND;

变成这样:

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

如果你暴露一个方法,接受一些值,比如说,毫秒,然后需要转换它,最好遵循java并发API的做法:

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

如果你真的非常需要常量,你仍然可以得到ie一小时内几秒通过调用:

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

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);
独行侠 2024-08-31 16:57:44

如果在android上,我建议:

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

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
明媚殇 2024-08-31 16:57:44

Java 8 / java.time 解决方案

作为 TimeUnit 的替代方案,您可能出于某种原因更喜欢 Duration 来自 java.time 包的类:

Duration.ofDays(1).getSeconds()     // returns 86400;
Duration.ofMinutes(1).getSeconds(); // 60
Duration.ofHours(1).toMinutes();    // also 60
//etc.

此外,如果您想更深入地分析 Duration.ofDays(..) 方法的工作原理,您将看到以下代码:

return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0);

其中 SECONDS_PER_DAY 是来自 LocalTime 类。

/**
 * 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.

我认为可以安全地假设,如果有任何包可以定义“所有烦人的时间常数,如毫秒/秒/分钟”,我相信 Java SDK 开发人员会使用它们。

为什么这个 LocalTime 常量包受到保护而不是公开,这是一个很好的问题,我相信这是有原因的。现在看起来你真的必须复制它们并自己维护。

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.

待天淡蓝洁白时 2024-08-31 16:57:44

Joda-Time 包含诸如 Days,其中包含诸如 toStandardSeconds()。所以你可以这样写:

int seconds = Days.ONE.toStandardSeconds();

虽然看起来有点冗长,也许只对更复杂的场景有用,比如闰年等。

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.

够运 2024-08-31 16:57:44

Java TimeUnit 似乎是你想要的

The Java TimeUnit seems to be what you want

花想c 2024-08-31 16:57:44

Joda Time 还有一个 DateTimeConstants 类诸如 MILLIS_PER_SECOND、SECONDS_PER_MINUTE、MILLIS_PER_DAY 等。

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

还如梦归 2024-08-31 16:57:44

这是我用来获取毫秒的方法。

import javax.management.timer.Timer;

Timer.ONE_HOUR
Timer.ONE_DAY
Timer.ONE_MINUTE
Timer.ONE_SECOND
Timer.ONE_WEEK

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
晨曦÷微暖 2024-08-31 16:57:44

虽然此答案中讨论了TimeUnit中讨论了Duration href="https://stackoverflow.com/a/35128143/642706">这个答案可能更直接地解决了这个问题,Java中还有一些其他方便的时间单位功能。

java.time

有关单位,请参阅 ChronoUnit 枚举:

  • 永远
  • ERAS
  • MILLENNIA
  • 世纪
  • 几十年
  • HALF_DAYS
  • 小时
  • 分钟
  • MILLIS
  • MICROS
  • NANOS

java.time 包 具有复杂的枚举 DayOfWeek。因此,您可以传递成熟的对象,例如 DayOfWeek.TUESDAYMonth.FEBRUARY,而不是仅仅传递数字或字符串。

java.time 框架还包括 MonthDayYearMonthYear 等类。同样,您可以传递成熟的对象而不仅仅是数字或字符串,以使您的代码更加自记录,确保有效值并提供类型安全。

TimeUnitChronoUnit 之间的转换

我们可以轻松地在 TimeUnitChronoUnit 之间进行转换。请参阅添加到旧类 TimeUnit 中的新方法。

ThreeTen-Extra

项目ThreeTen-Extra 项目提供了使用 java 的附加类。时间。其中包括:DayOfMonthDayOfYearAmPmQuarterYearQuarter>年周间隔代码>.

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.

ま昔日黯然 2024-08-31 16:57:44

另一种使用已烘焙(用于多次调用)Duration 实例(和 0 数学运算)的方法:

ChronoUnit.DAYS.getDuration().getSeconds()

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

ChronoUnit.DAYS.getDuration().getSeconds()
不必你懂 2024-08-31 16:57:44

如果这些常量用作编译时常量(例如,作为注释中的属性),那么 Apache DateUtils 将会派上用场。

import org.apache.commons.lang.time.DateUtils;
DateUtils.MILLIS_PER_SECOND
DateUtils.MILLIS_PER_MINUTE
DateUtils.MILLIS_PER_HOUR
DateUtils.MILLIS_PER_DAY

这些是原始的长常量。

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.

笙痞 2024-08-31 16:57:44
              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.

我想,自己创建它们是最简单的。您可以使用 DateCalendar 类来执行时间和日期的计算。使用 long 数据类型可处理大数,例如 UTC 1970 年 1 月 1 日以来的毫秒数、System.currentTimeMillis()

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

一抹苦笑 2024-08-31 16:57:44

如果您想获取值 Calendar 包含与时间管理相关的所有字段,通过一些简单的反射,您可以执行

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

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

这将输出:

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

您可以从中排除不需要的内容。

如果您只需要常量,则可以使用它们:Calendar.DAY_OF_MONTHCalendar.YEAR 等等。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文