获得正确的小时和分钟时出错

时间:2018-05-08 06:03:39

标签: java core

public class Testdate_time {

public void testdate() throws ParseException {

    String in_time = "2018 May 07 09:20:01 AM";
    String out_time = "2018 May 07 10:08:29 AM";
    int hours = 0;
    int mintues = 0;
    org.joda.time.format.DateTimeFormatter format = DateTimeFormat.forPattern("yyyy MMM dd hh:mm:ss a");
    DateTime date1 = format.parseDateTime(in_time);
    DateTime date2 = format.parseDateTime(out_time);
    hours = Hours.hoursBetween(date1, date2).getHours();

    String strhours = String.valueOf(hours).replaceAll("-", "");
    mintues = date1.getMinuteOfHour() - date2.getMinuteOfHour();
    String Strminutes = String.valueOf(mintues).replaceAll("-", "");
    System.out.println("hours" + strhours);
    System.out.println("minutes" + Strminutes);

}

public static void main(String[] args) throws ParseException {

    new Testdate_time().testdate();

}

我也使用了jodatime和simpledateformat http://www.joda.org/joda-time/userguide.html

输出:

hours0
minutes12

1 个答案:

答案 0 :(得分:1)

要正确计算两个日期之间的小时和分钟,使用Java 8 Time API并忽略夏令时,您可以这样做:

String in_time = "2018 May 07 09:20:01 AM";
String out_time = "2018 May 07 10:08:29 AM";
DateTimeFormatter format = DateTimeFormatter.ofPattern("uuuu MMM dd hh:mm:ss a", Locale.US);
LocalDateTime date1 = LocalDateTime.parse(in_time, format);
LocalDateTime date2 = LocalDateTime.parse(out_time, format);

long diff = ChronoUnit.MINUTES.between(date1, date2);
System.out.printf("%d hours %d minutes%n", diff / 60, diff % 60);

或者,如果您不想自己做数学运算,请使用Duration

Duration duration = Duration.between(date1, date2);
System.out.printf("%d hours %d minutes%n", duration.toHours(), duration.toMinutesPart());

输出(来自两者)

0 hours 48 minutes