Java

java获取年份与日期操作技巧

小樊
123
2024-07-14 09:17:22
栏目: 编程语言

  1. 获取当前日期的年份:
import java.util.Calendar;

Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
System.out.println("Current year: " + year);
  1. 获取指定日期的年份:
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);
  1. 增加或减少日期中的年份:
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));
  1. 计算两个日期之间的年份差:
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操作日期和年份的技巧,希望对你有所帮助。

0
看了该问题的人还看了