My English is poor, but I hope to describe it clearly
precondition: JDK 1.8
I need to create a tool class to handle the date: convert the input string to the date N days ago
Several of Date's constructors were found to be out of date during use: "@deprecated" , so I chose "Date(long date)" , but found problems with the handling of February
This method is to process strings into dates
public static Date stringToDate(String str) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date date = null;
try {
date = format.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Use "Date(long date)" (error)
public static Date getNDays(String str, int n) {
Calendar init = Calendar.getInstance();
init.set(1970,01,01,00,00,00);
Calendar calendar = Calendar.getInstance();
Date date = DateUtil.stringToDate(str);
calendar.setTime(date);
calendar.add(Calendar.DATE, -n);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
long begin = init.getTimeInMillis();
long now = calendar.getTimeInMillis();
return new Date(now - begin);
}

use "Date(int year, int month, int date, int hrs, int min, int sec)" but @deprecated (true)
public static Date getNDays(String str, int n) {
Calendar calendar = Calendar.getInstance();
Date date = DateUtil.stringToDate(str);
calendar.setTime(date);
calendar.add(Calendar.DATE, -n);
return new Date(
calendar.get(Calendar.YEAR) - 1900,
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY\_OF\_MONTH),
0,
0,
0
);
}
I hope to receive a reply,tanks!
email: 1710252399@vip.henu.edu.cn