一、Calender:
二、Date:
2.1)String to Date:
public static Date stringToDate(String dateStr, String pattern) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.parse(dateStr);
}
//Test:
System.out.println(stringToDate("20220101", "yyyyMMdd"));
System.out.println(stringToDate("2022-01-01", "yyyy-MM-dd"));
2.2)Date to String:
public static String dateToString(Date dateStr, String pattern) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(dateStr);
}
//Test:
System.out.println(dateToString(new Date(), "yyyyMMdd"));
System.out.println(dateToString(new Date(), "yyyy-MM-dd"));
2.3)加、减
public static Date addDays(Date date, int n) {
Calendar cal = Calendar.getInstance();
//设置起时间
cal.setTime(date);
//增加天n天
cal.add(Calendar.DATE, n);
return cal.getTime();
}
//Test:
System.out.println(addDays(new Date(), -1));
System.out.println(addDays(new Date(), 1));
2.4)日期差
public static int dateDifference(Date start, Date end) {
Calendar cal = Calendar.getInstance();
//设置起时间
cal.setTime(start);
int n = 0;
for (;;) {
//增加天1天
cal.add(Calendar.DATE, 1);
n = n + 1;
if (cal.getTime().compareTo(end) == 0) {
break;
}
}
return n;
}
//Test:
System.out.println(dateDifference(stringToDate("20220101", "yyyyMMdd"), stringToDate("20220102", "yyyyMMdd")));
2.5)获取两个日期中间的所有日期(包含起始日期)
public static List<Date> getBetweenDate(Date start, Date end) {
Set<Date> dateSet = new HashSet<>();
Calendar cal = Calendar.getInstance();
//设置起时间
cal.setTime(start);
int n = 0;
for (;;) {
dateSet.add(start);
//增加天1天
cal.add(Calendar.DATE, 1);
n = n + 1;
if (cal.getTime().compareTo(end) == 0) {
break;
}
dateSet.add(cal.getTime());
}
dateSet.add(end);
List<Date> dateList = new ArrayList<Date>(dateSet);
Collections.sort(dateList);
return dateList;
}
//Test:
System.out.println(getBetweenDate(stringToDate("20220101", "yyyyMMdd"), stringToDate("20220102", "yyyyMMdd")));
2.6)获取一周的第一天、最后一天
2.7)获取一月的第一天、最后一天
2.8)获取一年的第一天、最后一天
2.8)大小比较
三、DateTime:
3.1)String to DateTime:
3.2)DateTime to String:
四、LocalDate:
4.1)String to LocalDate:
4.2)LocalDate to String:
五、LocalDateTime:
5.1)String to LocalDate:
5.2)LocalDate to String: