按分钟比较日历时间

Compare calendar time by minutes

我想计算 "MON 17:00" 和 "Tue 5:00" 在 "minutes" 中的差异 如何使用 Java 实现此目的。我不太明白如何使用日历,simpleDateFormat 不支持 Mon,Tue,Wed,e.t.c 功能。有帮助吗?

问题只涉及周,因此 "SUN 00:00" 最早,"SAT 23:59" 最晚。

P.S。给定许多这种格式的字符串,我还想将它们从最先发生的到最后发生的排序。因为我认为先对它们进行排序会使任务(确定差异)更容易。

可能是这样的

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class DateCompare {

    public static void main(String[] args) {
        try {
            final String start = "Mon 17:00";
            final String end = "Tue 5:00";
            SimpleDateFormat formatter = new SimpleDateFormat("EEE HH:mm", Locale.US);
            long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(formatter.parse(end).getTime() - formatter.parse(start).getTime()); 
            System.out.println(diffMinutes + " minutes");
        } catch(Exception ex) {
            ex.printStackTrace();
        }

    }

}

Java 没有表示星期几(星期几和一天中的时间)的类型。我建议:

  • 使用 java.time,现代 Java 日期和时间 API。
  • 设计一个class代表你的时代。
  • 在您的内部 class 仅将您的时间表示为您决定的某个星期内的特定日期和时间。这将免费为您提供分钟排序和差异。

您的 class 可能如下所示:

/** A time of week like "MON 17:00". In other words a day of week and time of day. */
public class TimeOfWeek implements Comparable<TimeOfWeek> {

    private static DateTimeFormatter dayTimeFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("EEE H:mm")
            .toFormatter(Locale.ENGLISH);
    /** First day of the week used internally for date-times, Sun Dec 28, 1969 */
    private static LocalDate firstDate 
            = LocalDate.EPOCH.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));

    /**
     * Internal representation;
     * always within the week of the epoch, Sun Dec 28, 1969 through Sat Jan 3, 1970.
     */
    private LocalDateTime dateTime;

    public TimeOfWeek(String dayTimeString) {
        TemporalAccessor parsed = dayTimeFormatter.parse(dayTimeString);
        DayOfWeek dow = DayOfWeek.from(parsed);
        LocalTime time = LocalTime.from(parsed);
        dateTime = firstDate.with(TemporalAdjusters.nextOrSame(dow)).atTime(time);
        assert ! dateTime.isBefore(firstDate.atStartOfDay()) : dateTime;
        assert dateTime.isBefore(firstDate.plusWeeks(1).atStartOfDay()) : dateTime;
    }

    /** The order is by day of week, Sunday first, then by time of day. */
    @Override
    public int compareTo(TimeOfWeek other) {
        return this.dateTime.compareTo(other.dateTime);
    }

    /** @return The difference in minutes between this and other (signed) */
    int minutesUntil(TimeOfWeek other) {
        return Math.toIntExact(ChronoUnit.MINUTES.between(this.dateTime, other.dateTime));
    }

    @Override
    public String toString() {
        return dateTime.format(dayTimeFormatter);
    }
}

现在对 TimeOfWeek 个对象的列表进行排序:

    List<TimeOfWeek> dayTimes = Arrays.asList(new TimeOfWeek("Tue 5:00"),
            new TimeOfWeek("SAT 23:59"),
            new TimeOfWeek("SUN 00:00"),
            new TimeOfWeek("MON 17:00"));
    dayTimes.sort(Comparator.naturalOrder());
    System.out.println(dayTimes);

输出:

[Sun 0:00, Mon 17:00, Tue 5:00, Sat 23:59]

查找排序列表中对象之间的成对差异:

    for (int i = 1; i < dayTimes.size(); i++) {
        TimeOfWeek start = dayTimes.get(i - 1);
        TimeOfWeek end = dayTimes.get(i);
        System.out.println("Difference between " + start + " and " + end + ": "
                + start.minutesUntil(end) + " minutes");
    }
Difference between Sun 0:00 and Mon 17:00: 2460 minutes
Difference between Mon 17:00 and Tue 5:00: 720 minutes
Difference between Tue 5:00 and Sat 23:59: 6899 minutes

Link: Oracle tutorial: Date Time 解释如何使用 java.time.

如果不允许使用SimpleDateFormat,你最好使用Apache lang 3。

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.time.DateUtils;

public class DateCompare {

    public static void main(String[] args) {
        try {
            final String start = "MON 17:00";
            final String end = "Tue 5:00";
            List<Date> dates = Arrays.asList(DateUtils.parseDate(start, Locale.US, "EEE HH:mm"), DateUtils.parseDate(end, Locale.US, "EEE HH:mm"));
            Collections.sort(dates);
            long diffMinutes = TimeUnit.MILLISECONDS.toMinutes(dates.get(1).getTime() - dates.get(0).getTime()); 
            System.out.println(diffMinutes + " minutes");
        } catch(Exception ex) {
            ex.printStackTrace();
        }

    }

}