在 Java 中获取当前年份的整数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/136419/
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
Get integer value of the current year in Java
提问by karlgrz
I need to determine the current year in Java as an integer. I could just use java.util.Date()
, but it is deprecated.
我需要将 Java 中的当前年份确定为整数。我可以只使用java.util.Date()
,但它已被弃用。
采纳答案by cagcowboy
int year = Calendar.getInstance().get(Calendar.YEAR);
Not sure if this meets with the criteria of not setting up a new Calendar? (Why the opposition to doing so?)
不确定这是否符合不设置新日历的条件?(为什么反对这样做?)
回答by conmulligan
The easiest way is to get the year from Calendar.
最简单的方法是从日历中获取年份。
// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);
回答by toolkit
This simplest (using Calendar, sorry) is:
这个最简单的(使用日历,抱歉)是:
int year = Calendar.getInstance().get(Calendar.YEAR);
There is also the new Date and Time API JSR, as well as Joda Time
回答by Alan
If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because java.util.Date
is mutable. java.util.Calendar
has performance problems when its fields get updated, and is clunky for datetime arithmetic.
如果您的应用程序大量使用 Date 和 Calendar 对象,您真的应该使用 Joda Time,因为它java.util.Date
是可变的。java.util.Calendar
当其字段更新时会出现性能问题,并且对于日期时间算法来说很笨重。
回答by maxp
I use special functions in my library to work with days/month/year ints -
我在我的库中使用特殊函数来处理天/月/年整数 -
int[] int_dmy( long timestamp ) // remember month is [0..11] !!!
{
Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp );
return new int[] {
cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR )
};
};
int[] int_dmy( Date d ) {
...
}
回答by Ewan Makepeace
You can do the whole thing using Integer math without needing to instantiate a calendar:
您可以使用整数数学来完成整个事情,而无需实例化日历:
return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);
May be off for an hour or two at new year but I don't get the impression that is an issue?
新年可能会休息一两个小时,但我不觉得这是个问题?
回答by basZero
If you want the year of any date object, I used the following method:
如果你想要任何日期对象的年份,我使用了以下方法:
public static int getYearFromDate(Date date) {
int result = -1;
if (date != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.YEAR);
}
return result;
}
回答by maral04
As some people answered above:
正如上面一些人回答的那样:
If you want to use the variable later, better use:
如果您想稍后使用该变量,最好使用:
int year;
year = Calendar.getInstance().get(Calendar.YEAR);
If you need the year for just a condition you better use:
如果您只需要年份作为条件,您最好使用:
Calendar.getInstance().get(Calendar.YEAR)
For example using it in a do while that checks introduced year is not less than the current year-200 or more than the current year (Could be birth year):
例如在 do while 中使用它,检查引入的年份不小于当前年份 - 200 或大于当前年份(可能是出生年份):
import java.util.Calendar;
import java.util.Scanner;
public static void main (String[] args){
Scanner scannernumber = new Scanner(System.in);
int year;
/*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/
do{
System.out.print("Year (Between "+((Calendar.getInstance().get(Calendar.YEAR))-200)+" and "+Calendar.getInstance().get(Calendar.YEAR)+") : ");
year = scannernumber.nextInt();
}while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));
}
回答by Raffi Khatchadourian
回答by Basil Bourque
tl;dr
tl;博士
ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) )
.getYear()
Time Zone
时区
The answerby Raffi Khatchadourianwisely shows how to use the new java.time packagein Java 8. But that answer fails to address the critical issue of time zone in determining a date.
答案由拉菲Khatchadourian明智地展示了如何使用新的java.time包中的Java 8.但是这个答案未能解决时区的关键问题在确定的日期。
int year = LocalDate.now().getYear();
int year = LocalDate.now().getYear();
That code depends on the JVM's current default time zone. The default zone is used in determining what today's date is. Remember, for example, that in the moment after midnight in Paris the date in Montréal is still 'yesterday'.
该代码取决于 JVM 当前的默认时区。默认区域用于确定今天的日期。请记住,例如,在巴黎午夜过后的那一刻,蒙特利尔的日期仍然是“昨天”。
So your results may vary by what machine it runs on, a user/admin changing the host OS time zone, or any Java code at any momentchanging the JVM's current default. Better to specify the time zone.
因此,您的结果可能会因运行的机器、用户/管理员更改主机操作系统时区或任何 Java 代码在任何时候更改 JVM 的当前默认值而有所不同。最好指定时区。
By the way, always use proper time zone namesas defined by the IANA. Never use the 3-4 letter codes that are neither standardized nor unique.
顺便说一句,一定要使用正确的时区的名称作为由IANA规定。切勿使用既不标准化也不唯一的 3-4 个字母代码。
java.time
时间
Example in java.time of Java 8.
Java 8 的 java.time 中的示例。
int year = ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) ).getYear() ;
Joda-Time
乔达时间
Some idea as above, but using the Joda-Time2.7 library.
上面的一些想法,但使用Joda-Time2.7 库。
int year = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getYear() ;
Incrementing/Decrementing Year
递增/递减年份
If your goal is to jump a year at a time, no need to extract the year number. Both Joda-Time and java.time have methods for adding/subtracting a year at a time. And those methods are smart, handling Daylight Saving Time and other anomalies.
如果您的目标是一次跳转一年,则无需提取年份编号。Joda-Time 和 java.time 都有一次加/减一年的方法。这些方法很聪明,可以处理夏令时和其他异常情况。
Example in Joda-Time 2.7.
Joda-Time 2.7 中的示例。
DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).minusYears( 1 ) ;