如何在给出时间时找到时差

时间:2012-07-06 11:01:50

标签: java

我有时间采用以下格式。

String deptTime ="08:00 PM";
String arrTime = "04:00 AM";

如何在 1小时30分钟 ..

等词语中准确区分小时数

2 个答案:

答案 0 :(得分:1)

    Calendar cal1 = Calendar.getInstance();
    cal1.set(Calendar.HOUR, 8);
    cal1.set(Calendar.AM_PM, Calendar.PM);


    Calendar cal2 = Calendar.getInstance();
    cal2.set(Calendar.HOUR, 4);
    cal2.set(Calendar.AM_PM, Calendar.AM);
    System.out.println(((cal1.getTimeInMillis()-cal2.getTimeInMillis())/1000)/3600);

答案 1 :(得分:0)

使用apache commons-lang jar文件.. 将deptTime和arrTime作为 StringBuffer

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Calendar calendar = Calendar.getInstance();
    String dateIs = dateFormat.format(calendar.getTime());
    if (departureTime.reverse().substring(0,2).equalsIgnoreCase(arrivalTime.reverse().substring(0,2))) {
        departureTime.reverse().insert(0, dateIs + " ");
        arrivalTime.reverse().insert(0, dateIs + " ");
    } else {
        departureTime.reverse().insert(0, dateIs + " ");
        calendar.add(Calendar.DATE, 1);
        arrivalTime.reverse().insert(0,dateFormat.format(calendar.getTime()) +" ");
    }
    dateFormat.applyPattern("dd/MM/yyyy hh:mm aa");
    Date dateOne = dateFormat.parse(departureTime.toString());
    Date dateTwo = dateFormat.parse(arrivalTime.toString());

    DurationFormatUtils.formatDurationHMS(dateTwo.getTime() - dateOne.getTime());
    System.out.println(DurationFormatUtils.formatDurationWords(dateTwo.getTime() -
                                                               dateOne.getTime(),
                                                               true, true));