本地时间解析器不起作用[java]

时间:2018-05-18 08:24:40

标签: java

在问题下面我已经放了我的代码。出于某种原因,它无法解析6:00和17:30到本地时间,然后在ifstatetement中将其作为布尔值,如果是在6:00之前放入nachtMap中的值,如果是在17:30之后,也将它放在NachtMap中,否则放在Daymap中(它基本上都在for循环中)。 谁知道我的代码是什么wron wron?

// for each license plate
            for (int i = 1, n = licenseplateList.size(); i < n; i++) {

                //first look at whether it is considered as day or night time


                try {

                    String time1Str = begintimeList.get(i);
                String time2Str = endingtimeList.get(i);

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
                LocalTime time1 = LocalTime.parse(time1Str, formatter);
                LocalTime time2 = LocalTime.parse(time2Str, formatter);

                // add date value: start with today
                LocalDate today = LocalDate.now();
                // lower value will be assigned to today
                LocalDateTime dateTime1 = LocalDateTime.of(today, time1);
                // upper value will be assigned same day if it is after lower value
                // otherwise (we crossed date boundary) assign it to tomorrow
                LocalDateTime dateTime2 =   time2.isAfter(time1) ?
                        LocalDateTime.of(today, time2) : LocalDateTime.of(today.plusDays(1), time2);

                Duration duration = Duration.between(dateTime1, dateTime2);
                Duration halfDuration = duration.dividedBy(2);
                LocalTime result = LocalTime.from(halfDuration.addTo(time1));

                System.out.println(result.format(formatter));

                LocalTime calc = LocalTime.parse("6:00");
                LocalTime calc2 = LocalTime.parse("17:30");
                boolean before = result.format(formatter).before(calc);
                boolean after = result.format(formatter).after(calc2);

                if (before == true) {
                    nachtMap.put(licenseplateList.get(i), kmperlineList.get(i)); 

                }
                else {
                    if(after == true) {

                        nachtMap.put(licenseplateList.get(i), kmperlineList.get(i));
                    }
                    else {
                        dagMap.put(licenseplateList.get(i), kmperlineList.get(i));
                    }
                }

            }catch (Exception e) {
            }

1 个答案:

答案 0 :(得分:0)

也许您应该使用H:mm代替HH:mm,它可以解析06:006:00

@Test
public void test() {
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H:mm");
    Assert.assertEquals(
        LocalTime.parse("6:00", formatter),
        LocalTime.parse("06:00", formatter)
    );
}