Java中的时间常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2442486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Time consts in Java?
提问by Yossale
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 包包含所有烦人的时间常数,例如一分钟/小时/天/年中的毫秒/秒/分钟?我不想复制这样的东西。
采纳答案by Brian Agnew
Joda-Timecontains classes such as Days, which contain methods such as toStandardSeconds(). So you can write:
Joda-Time包含诸如Days 之类的类,其中包含诸如toStandardSeconds() 之类的方法。所以你可以写:
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.
虽然它看起来有点冗长,也许只对更复杂的场景有用,比如闰年等。
回答by Pindatjuh
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()
.
我想,自己创建它们是最简单的。您可以使用Date
和Calendar
类来执行时间和日期的计算。使用long
数据类型处理大数字,例如从 1 Januari 1970 UTC 开始的毫秒数,System.currentTimeMillis()
.
回答by duffymo
I doubt it, because they aren't all constants. The number of milliseconds for a year varies, right?
我对此表示怀疑,因为它们并非都是常数。一年的毫秒数会有所不同,对吗?
回答by Hyman
If you mean to obtain the values Calendar
have all fields related to time management, with some simple reflection you can do
如果您的意思是获取Calendar
所有与时间管理相关的字段的值,您可以进行一些简单的反思
Field[] fields = Calendar.class.getFields();
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..
如果您只需要常量,则可以使用它们:Calendar.DAY_OF_MONTH
,Calendar.YEAR
等等..
回答by theadam
I would go with java TimeUnitif you are not including joda-time in your project already. You don't need to include an external lib and it is fairly straightforward.
如果您的项目中没有包含 joda-time,我会使用 java TimeUnit。您不需要包含外部库,而且相当简单。
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.
每当您需要那些“烦人的常数”时,您通常需要它们将一些数字相乘以进行跨单位转换。相反,您可以使用 TimeUnit 来简单地转换值而无需显式乘法。
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:
如果您公开一个接受某些值的方法,例如,millis 然后需要转换它,最好遵循 java 并发 API 的作用:
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:
如果您真的非常需要常量,您仍然可以通过调用在一个小时内获得 ie 秒:
int secondsInHour = TimeUnit.HOURS.toSeconds(1);
回答by Lindsay Thurmond
Joda Time also has a DateTimeConstants
class with things like MILLIS_PER_SECOND, SECONDS_PER_MINUTE, MILLIS_PER_DAY, etc, etc.
Joda Time 也有一个DateTimeConstants
类,其中包含 MILLIS_PER_SECOND、SECONDS_PER_MINUTE、MILLIS_PER_DAY 等内容。
回答by Oded Breiner
If on android, I suggest:
如果在android上,我建议:
DateUtils.SECOND_IN_MILLIS
DateUtils.MINUTE_IN_MILLIS
DateUtils.HOUR_IN_MILLIS
DateUtils.DAY_IN_MILLIS
DateUtils.WEEK_IN_MILLIS
DateUtils.YEAR_IN_MILLIS
回答by Basil Bourque
While TimeUnit
discussed in this Answerand Duration
discussed in this Answerprobably more directly addresses the Question, there are some other handy units-of-time features in Java.
虽然TimeUnit
在讨论这个答案,并Duration
在讨论这个答案可能更直接解决的问题,也有一些其他方便的单位-的时间特征在Java中。
java.time
时间
For units, see the ChronoUnit
enum:
对于单位,请参见ChronoUnit
枚举:
FOREVER
ERAS
MILLENNIA
CENTURIES
DECADES
YEARS
MONTHS
WEEKS
DAYS
HALF_DAYS
HOURS
MINUTES
SECONDS
MILLIS
MICROS
NANOS
FOREVER
ERAS
MILLENNIA
CENTURIES
DECADES
YEARS
MONTHS
WEEKS
DAYS
HALF_DAYS
HOURS
MINUTES
SECONDS
MILLIS
MICROS
NANOS
The java.time packagehas 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
.
该java.time包具有复杂的枚举DayOfWeek
和Month
。因此,您可以传递完整的对象,例如DayOfWeek.TUESDAY
或,而不是仅仅传递数字或字符串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.
所述java.time框架还包括类,如MonthDay
,YearMonth
,和Year
。同样,您可以传递完整的对象,而不仅仅是数字或字符串,以使您的代码更具自文档性、确保有效值并提供类型安全性。
ThreeTen-Extra project
ThreeTen-Extra项目
The ThreeTen-Extraproject provides additional classes to work with java.time. These include: DayOfMonth
, DayOfYear
, AmPm
, Quarter
, YearQuarter
, YearWeek
, Days
, Weeks
, Months
, Years
, and Interval
.
该ThreeTen-EXTRA项目提供额外的类与java.time工作。这些措施包括:DayOfMonth
,DayOfYear
,AmPm
,Quarter
,YearQuarter
,YearWeek
,Days
,Weeks
,Months
,Years
,和Interval
。
回答by Mateusz Szulc
Java 8 / java.time solution
Java 8 / java.time 解决方案
As an alternative to TimeUnit
, you might for some reason prefer the Durationclass from java.timepackage:
作为 的替代TimeUnit
,您可能出于某种原因更喜欢java.time包中的Duration类:
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:
此外,如果您更深入地分析 Duration.ofDays(..) 方法的工作原理,您将看到以下代码:
return create(Math.multiplyExact(days, SECONDS_PER_DAY), 0);
where SECONDS_PER_DAY
is a package protected static constant from LocalTimeclass.
哪里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.
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.
我认为可以安全地假设,如果有任何包定义“所有烦人的时间常数,如毫秒/秒/分钟”,我相信 Java SDK 开发人员会使用它们。
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.
为什么这个LocalTime
常量包是受保护的而不是公开的,这是一个好问题,我相信这是有原因的。现在看起来你真的必须复制它们并自己维护。