任务描述
本关任务:计算两个日期之间的间隔时间。
/**
* 计算两个日期之间的间隔时间
*/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Test {
public static String getTime(Date d1,Date d2) {
// 请在下面的Begin-End之间编写正确的代码
/********** Begin **********/
Calendar cd1 = Calendar.getInstance();
Calendar cd2 = Calendar.getInstance();
cd1.setTime(d1);
cd2.setTime(d2);
int d = cd2.get(Calendar.DAY_OF_YEAR) - cd1.get(Calendar.DAY_OF_YEAR);
if (d < 1) {
int h = cd2.get(Calendar.HOUR_OF_DAY)
- cd1.get(Calendar.HOUR_OF_DAY);
if (h < 1) {
int m = cd2.get(Calendar.MINUTE) - cd1.get(Calendar.MINUTE);
if (m == 0) {
return "刚刚";
} else {
return m + "分钟前";
}
} else {
return h + "小时前";
}
} else {
return d + "天前";
}
/********** End **********/
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String d1 = scanner.next();
String d2 = scanner.next();
SimpleDateFormat sft = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
Date aDate = null;
Date bDate = null;
try {
aDate = sft.parse(d1);
bDate = sft.parse(d2);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.print("距离上一个时间过去了多久:"+getTime(aDate,bDate));
}
}