一、代码示例
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);
}
}
二、截图示例
文章来源地址https://www.toymoban.com/news/detail-724194.html
文章来源:https://www.toymoban.com/news/detail-724194.html
到了这里,关于【java】获取当前年份的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!