バックエンド:Java計算時間差


一、日、時、分を別々に計算する
/**
*  SimpleDateFormat     
* @throws ParseException 
*/
public static void calculateTimeDifferenceBySimpleDateFormat() throws ParseException {
    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    /*   */
    Date fromDate1 = simpleFormat.parse("2018-03-01 12:00");  
    Date toDate1 = simpleFormat.parse("2018-03-12 12:00");  
    long from1 = fromDate1.getTime();  
    long to1 = toDate1.getTime();  
    int days = (int) ((to1 - from1) / (1000 * 60 * 60 * 24));  
    System.out.println("           :" + days);

    /*   */
    Date fromDate2 = simpleFormat.parse("2018-03-01 12:00");  
    Date toDate2 = simpleFormat.parse("2018-03-12 12:00");  
    long from2 = fromDate2.getTime();  
    long to2 = toDate2.getTime();  
    int hours = (int) ((to2 - from2) / (1000 * 60 * 60));
    System.out.println("           :" + hours);

    /*   */
    Date fromDate3 = simpleFormat.parse("2018-03-01 12:00");  
    Date toDate3 = simpleFormat.parse("2018-03-12 12:00");  
    long from3 = fromDate3.getTime();  
    long to3 = toDate3.getTime();  
    int minutes = (int) ((to3 - from3) / (1000 * 60));  
    System.out.println("           :" + minutes);
}

結果:
2つの時間の間の日数の差は11です.
2時間の時間差:264
2つの時間の間の分の差は15840です.
 
二、正確に秒まで
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Date parse = format.parse("20180321141111");
		Date date = format.parse("20180321141111");
		long between = date.getTime() - parse.getTime();
		long day = between / (24 * 60 * 60 * 1000);
		long hour = (between / (60 * 60 * 1000) - day * 24);
		long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		System.out.println(day + " " + hour + "  " + min + " " + s + " ");

 
 
まとめ:時間をミリ秒に変換し、差分値を計算し、対応するフォーマットに変換します.