001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools.date;
003
004import java.time.Instant;
005import java.time.format.DateTimeFormatter;
006import java.time.format.FormatStyle;
007import java.util.Objects;
008
009import org.openstreetmap.josm.tools.Utils;
010
011/**
012 * A timespan defined by a start and end instant.
013 */
014public final class Interval {
015
016    private final Instant start;
017    private final Instant end;
018
019    /**
020     * Constructs a new {@code Interval}
021     * @param start start instant
022     * @param end end instant
023     */
024    public Interval(Instant start, Instant end) {
025        this.start = start;
026        this.end = end;
027    }
028
029    /**
030     * Returns an ISO 8601 compatible string
031     * @return an ISO 8601 compatible string
032     */
033    @Override
034    public String toString() {
035        return start + "/" + end;
036    }
037
038    /**
039     * Formats the interval of the given track as a human readable string
040     * @return The interval as a string
041     */
042    public String format() {
043        String ts = "";
044        DateTimeFormatter df = DateUtils.getDateFormatter(FormatStyle.SHORT);
045        String earliestDate = df.format(getStart());
046        String latestDate = df.format(getEnd());
047
048        if (earliestDate.equals(latestDate)) {
049            DateTimeFormatter tf = DateUtils.getTimeFormatter(FormatStyle.SHORT);
050            ts += earliestDate + ' ';
051            ts += tf.format(getStart()) + " \u2013 " + tf.format(getEnd());
052        } else {
053            DateTimeFormatter dtf = DateUtils.getDateTimeFormatter(FormatStyle.SHORT, FormatStyle.MEDIUM);
054            ts += dtf.format(getStart()) + " \u2013 " + dtf.format(getEnd());
055        }
056
057        ts += String.format(" (%s)", Utils.getDurationString(getEnd().toEpochMilli() - getStart().toEpochMilli()));
058        return ts;
059    }
060
061    /**
062     * Returns start instant.
063     * @return start instant
064     */
065    public Instant getStart() {
066        return start;
067    }
068
069    /**
070     * Returns end instant.
071     * @return end instant
072     */
073    public Instant getEnd() {
074        return end;
075    }
076
077    @Override
078    public boolean equals(Object o) {
079        if (this == o) return true;
080        if (!(o instanceof Interval)) return false;
081        Interval interval = (Interval) o;
082        return Objects.equals(start, interval.start) && Objects.equals(end, interval.end);
083    }
084
085    @Override
086    public int hashCode() {
087        return Objects.hash(start, end);
088    }
089}