-1

I'd like to calculate the difference between "MON 17:00" and "Tue 5:00" in "minutes" How can I achieve this using Java. I don't quite understand how to use calendar and simpleDateFormat doesn't support the Mon,Tue,Wed,e.t.c feature. Any help?

The problem only involves week therefore "SUN 00:00" as the earliest and "SAT 23:59" as the latest.

P.S. given many strings in that format, I also would like to sort them from what happens first, to what happens last. Because I think sorting them first would make the task (determining the difference) easier.

preciousbetine
  • 2,959
  • 3
  • 13
  • 29
Karl Garcia
  • 45
  • 11

3 Answers3

1

May be something like this

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();
        }

    }

}
Miller Cy Chan
  • 897
  • 9
  • 19
  • That is brilliant! I couldn't find that EEE simple date format! one last thing. how can I sort them from earliest to latest? – Karl Garcia Dec 20 '18 at 02:22
  • (off topic) crap can't upvote due to low reputation. – Karl Garcia Dec 20 '18 at 02:25
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Dec 20 '18 at 11:30
1

Java doesn’t have a type that represents a time of week (day of week and time of day). I suggest:

  • Use java.time, the modern Java date and time API.
  • Design a class to represent your times.
  • Internally in your class only represent your time as a specific date and time in some week that you decide. This will give you sorting and difference in minutes for free.

Your class may look like this:

/** 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);
    }
}

Now to sort a list of TimeOfWeek objects:

    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);

Output:

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

To find the pairwise differences between the objects in the sorted list:

    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 explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

If not allowed to use SimpleDateFormat, you'd better use 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();
        }

    }

}
Miller Cy Chan
  • 897
  • 9
  • 19