将星期几与时间排序

时间:2018-12-20 11:43:00

标签: java java-date

我希望排序从星期日的00:00开始。我的问题是该代码的零开始于星期四的8:00。我按分钟数排序,但零开始于8:00。

到目前为止,这是我的代码。

String[] lines = S.split("\n");
System.out.println(Arrays.toString(lines));

int longest = 0;
try {
    for (int i = 0; i < lines.length - 1; i++) {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE HH:mm-HH:mm", Locale.US);
        long diffMinutes;
        diffMinutes = TimeUnit.MILLISECONDS.toMinutes(
                            formatter.parse(lines[i + 1]).getTime() - 
                            formatter.parse(lines[i]).getTime());
        if (longest < diffMinutes) {
            longest = (int) diffMinutes;
        }
    }
} catch (ParseException e) {
    e.printStackTrace();
}
return longest;

该函数采用这样的字符串

"Mon 01:00-23:00\\nTue 01:00-23:00\\nWed 01:00-23:00\\nThu 01:00-23:00\\nFri 01:00-23:00\\nSat 01:00-23:00\\nSun 01:00-21:00"

程序将字符串切成薄片并将其存储在数组行中,然后我试图对其进行排序。

1 个答案:

答案 0 :(得分:1)

我认为可以通过应用更多拆分来解决此问题,这是因为您的String周期表示为 from-to 而不是诸如 1320(分钟)。我会使用java.time,尤其是LocalTimeDuration来进行正确的计算和比较。

我的代码基本上利用辅助方法执行以下操作(请参阅代码注释):

  1. "\n"
  2. 分割输入
  3. 按空格分隔第一步的每个结果,以便将星期几与一天中的时间分开
  4. 将第二次拆分的第二个结果除以"-",以获取一天中的时间
  5. 将结果转换为适当的对象
  6. 将它们存储在适当的数据结构中
  7. 找到最大持续时间

这是我想出的:

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.TextStyle;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

class WeekdayDurationHandler {

    public static void main(String[] args) {
        // input String splitting...
        String input = "Mon 01:00-23:00\nTue 01:00-23:00\nWed 01:00-23:00\nThu 01:00-23:00\nFri 01:00-23:00\nSat 01:00-23:00\nSun 01:00-21:00";
        String[] times = input.split("\n");

        // data structure for holding the durations per day
        Map<DayOfWeek, Duration> weekdayDurations = new TreeMap<>();

        // the result of the first splitting is unparseable, that's why some more
        // splitting is applied
        for (String s : times) {
            // separate the day of week from the time duration
            String[] sp = s.split(" ");
            // split the duration into "from" and "to" (time of day)
            String[] tp = sp[1].split("-");
            // parse the day of week into an appropriate object
            DayOfWeek dayOfWeek = parseDayOfWeek(sp[0]);
            // parse the times of day into appropriate objects
            LocalTime localTimeFrom = LocalTime.parse(tp[0]);
            LocalTime localTimeTo = LocalTime.parse(tp[1]);
            // calculate the duration between "from" and "to" time of day
            Duration duration = Duration.between(localTimeFrom, localTimeTo);
            // store them in the data structure
            weekdayDurations.put(dayOfWeek, duration);
        }

        // print them
        weekdayDurations.forEach((DayOfWeek dayOfWeek, Duration duration) -> {
            System.out.println(dayOfWeek.getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault()) + ": "
                    + duration.toHours() + " hours (" + duration.toMinutes() + " minutes)");
        });

        System.out.println("######################################################");

        // then print the maximum durations found
        findMaxDurationsFrom(weekdayDurations).forEach((DayOfWeek dayOfWeek, Duration duration) -> {
            System.out.println(dayOfWeek.getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault()) + ": "
                    + duration.toHours() + " hours (" + duration.toMinutes() + " minutes)");
        });
    }

    private static DayOfWeek parseDayOfWeek(String weekday) {
        switch (weekday.toLowerCase()) {
        case "mon":
            return DayOfWeek.MONDAY;
        case "tue":
            return DayOfWeek.TUESDAY;
        case "wed":
            return DayOfWeek.WEDNESDAY;
        case "thu":
            return DayOfWeek.THURSDAY;
        case "fri":
            return DayOfWeek.FRIDAY;
        case "sat":
            return DayOfWeek.SATURDAY;
        case "sun":
            return DayOfWeek.SUNDAY;
        default:
            throw new RuntimeException("Unparsable weekday: \"" + weekday + "\"");
        }
    }

    private static Map<DayOfWeek, Duration> findMaxDurationsFrom(Map<DayOfWeek, Duration> weekDurations) {
        final Map<DayOfWeek, Duration> maxDurations = new TreeMap<>();
        // find the maximum duration as a reference for all equal durations
        Duration maxDuration = findMaxDuration(weekDurations);
        // go through all durations and store those equal to maxDuration (no matter what day of week)
        weekDurations.forEach((DayOfWeek dayOfWeek, Duration duration) -> {
            if (duration.equals(maxDuration)) {
                maxDurations.put(dayOfWeek, duration);
            }
        });

        return maxDurations;
    }

    private static <K, V extends Comparable<V>> V findMaxDuration(Map<K, V> map) {
        Entry<K, V> maxEntry = Collections.max(map.entrySet(),
                (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue().compareTo(e2.getValue()));
        return maxEntry.getValue();
    }
}

我希望对您有帮助...