两个时间进行年月日时分秒操作
public static void testDate(Date timeOneForDate,Date timeTowForDate) throws ParseException {
Calendar cal=Calendar.getInstance();
SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("HH:mm:ss");
String date = dateFormat1.format(timeOneForDate);
String timeOne = dateFormat2.format(timeOneForDate);
String timeTow = dateFormat2.format(timeTowForDate);
String[] dateOne = date.split("-");
int yearOne = Integer.parseInt(dateOne[0]);
int monthOne = Integer.parseInt(dateOne[1]);
int dayOne = Integer.parseInt(dateOne[2]);
String[] splitOne = timeOne.split(":");
int hhOne = Integer.parseInt(splitOne[0]);
int mmOne = Integer.parseInt(splitOne[1]);
int ssOne = Integer.parseInt(splitOne[2]);
cal.set(Calendar.YEAR,yearOne);
cal.set(Calendar.MONTH,(monthOne - 1));
cal.set(Calendar.DAY_OF_MONTH,dayOne);
cal.set(Calendar.HOUR_OF_DAY, hhOne);
cal.set(Calendar.MINUTE, mmOne);
cal.set(Calendar.SECOND, ssOne);
System.out.println("未进行计算的时间:\t"+dateFormat3.format(cal.getTime()));
String[] splitTow = timeTow.split(":");
int hhTow = Integer.parseInt(splitTow[0]);
int mmTow = Integer.parseInt(splitTow[1]);
int ssTow = Integer.parseInt(splitTow[2]);
cal.add(Calendar.DAY_OF_MONTH,0);
cal.add(Calendar.HOUR_OF_DAY, (hhTow * 1));
cal.add(Calendar.MINUTE, (mmTow * -1));
cal.add(Calendar.SECOND, (ssTow * -1));
System.out.println("已进行计算的时间:\t"+dateFormat3.format(cal.getTime()));
}
简单调用
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date timeOneForDate = dateFormat1.parse("2020-12-31 20:00:00");
Date timeTowForDate = dateFormat1.parse("2020-10-10 10:30:30");
testDate(timeOneForDate,timeTowForDate);
}
得到结果
未进行计算的时间: 2020-12-31 20:00:00
已进行计算的时间: 2021-01-01 05:29:30