一、代码示例
package com.learning;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.util.Calendar;
import java.util.Date;
/**
* 获取当前年份
*/
public class GetCurrentYear {
public static void main(String[] args) {
System.out.println(getCurrentYearByCalendar());
System.out.println(getCurrentYearByYear());
System.out.println(getCurrentYearBySimpleDateFormat());
System.out.println(getCurrentYearByLocalDate());
}
/**
* 通过日历类Calendar获取当前年份
* @return
*/
public static String getCurrentYearByCalendar() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
return String.valueOf(year);
}
/**
* 通过Year类获取当前年份
*/
public static String getCurrentYearByYear(){
Year year = Year.now();
int yearValue = year.getValue();
return String.valueOf(yearValue);
}
/**
* 通过SimpleDateFormat获取当前年份
*/
public static String getCurrentYearBySimpleDateFormat(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
return simpleDateFormat.format(new Date());
}
/**
* 通过LocalDate类获取当前年份
* jdk8及以上
*/
public static String getCurrentYearByLocalDate(){
LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
return String.valueOf(year);
}
}
二、截图示例