- 获取当前日期的年份:
import java.util.Calendar; Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); System.out.println("Current year: " + year);
- 获取指定日期的年份:
import java.text.SimpleDateFormat; import java.util.Date; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse("2022-05-10"); Calendar cal = Calendar.getInstance(); cal.setTime(date); int year = cal.get(Calendar.YEAR); System.out.println("Year of specified date: " + year);
- 增加或减少日期中的年份:
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Calendar; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse("2022-05-10"); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.YEAR, 1); // 增加1年 //cal.add(Calendar.YEAR, -1); // 减少1年 Date newDate = cal.getTime(); System.out.println("New date after adding 1 year: " + sdf.format(newDate));
- 计算两个日期之间的年份差:
import java.text.SimpleDateFormat; import java.util.Date; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = sdf.parse("2022-05-10"); Date date2 = sdf.parse("2020-03-15"); Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); int diffYears = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR); System.out.println("Years difference between two dates: " + Math.abs(diffYears));
这些是一些常用的Java操作日期和年份的技巧,希望对你有所帮助。