我需要在Java中确定当前年份为整数。我可以只使用java.util.Date(),但已弃用。
当前回答
如果你想要任何日期对象的年份,我使用以下方法:
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;
}
其他回答
如果您的应用程序大量使用Date和Calendar对象,那么您确实应该使用Joda Time,因为java.util.Date是可变的。calendar在字段更新时存在性能问题,并且对于日期时间算法来说很笨拙。
如果你想要任何日期对象的年份,我使用以下方法:
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;
}
使用Java 8的时间API(假设你很高兴得到系统默认时区中的年份),你可以使用year::now方法:
int year = Year.now().getValue();
你也可以使用Java 8的LocalDate:
import java.time.LocalDate;
//...
int year = LocalDate.now().getYear();
在java 8中使用以下代码:
LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int date = localDate.getDayOfMonth();
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 解析日期字符串并更改格式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder