cag*_*boy 594
int year = Calendar.getInstance().get(Calendar.YEAR);
Run Code Online (Sandbox Code Playgroud)
不确定这是否符合不设置新日历的标准?(为什么反对这样做?)
ass*_*ias 118
使用Java 8的时间API(假设您很高兴在系统的默认时区中获得年份),您可以使用以下Year::now
方法:
int year = Year.now().getValue();
Run Code Online (Sandbox Code Playgroud)
too*_*kit 25
这个最简单的(使用Calendar,抱歉)是:
int year = Calendar.getInstance().get(Calendar.YEAR);
Run Code Online (Sandbox Code Playgroud)
还有新的Date和Time API JSR,以及Joda Time
con*_*gan 13
最简单的方法是从日历中获取年份.
// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);
Run Code Online (Sandbox Code Playgroud)
小智 12
您也可以使用java.time.YearMonth
(自Java 8开始)的2个方法:
import java.time.YearMonth;
...
int year = YearMonth.now().getYear();
int month = YearMonth.now().getMonthValue();
Run Code Online (Sandbox Code Playgroud)
bas*_*ero 10
如果你想要任何日期对象的年份,我使用以下方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) )
.getYear()
Run Code Online (Sandbox Code Playgroud)
答案由拉菲Khatchadourian明智地展示了如何使用新的java.time包中的Java 8.但是这个答案未能解决时区的关键问题在确定的日期.
int year = LocalDate.now().getYear();
该代码取决于JVM的当前默认时区.默认区域用于确定今天的日期.记住,例如,在巴黎午夜之后,蒙特利尔的日期仍然是"昨天".
所以,你的结果可能会受到它运行在什么机器,用户/管理员更改主机操作系统的时区,或任何Java代码改变在任何时刻改变JVM的当前默认值.最好指定时区.
顺便说一句,一定要使用正确的时区的名称作为由IANA规定.切勿使用既不标准也不唯一的3-4字母代码.
Java 8的java.time中的示例.
int year = ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) ).getYear() ;
Run Code Online (Sandbox Code Playgroud)
一些想法如上,但使用Joda-Time 2.7库.
int year = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getYear() ;
Run Code Online (Sandbox Code Playgroud)
如果您的目标是一次跳一年,则无需提取年份数.Joda-Time和java.time都有一次添加/减去一年的方法.这些方法很聪明,处理夏令时和其他异常情况.
Joda-Time 2.7中的示例.
DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).minusYears( 1 ) ;
Run Code Online (Sandbox Code Playgroud)
您还可以使用 Java 8 的LocalDate
:
import java.time.LocalDate;
//...
int year = LocalDate.now().getYear();
Run Code Online (Sandbox Code Playgroud)
对 java 8 使用以下代码:
LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int date = localDate.getDayOfMonth();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
422767 次 |
最近记录: |