1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.health.connect.datatypes; 18 19 import android.annotation.NonNull; 20 21 import java.time.Instant; 22 import java.util.Objects; 23 24 /** 25 * Represents time interval. 26 * 27 * <p>Each object has start time and end time. End time must be after start time. 28 * 29 * @hide 30 */ 31 public final class TimeInterval implements Comparable<TimeInterval> { 32 33 @Override compareTo(TimeInterval interval)34 public int compareTo(TimeInterval interval) { 35 if (getStartTime().compareTo(interval.getStartTime()) != 0) { 36 return getStartTime().compareTo(interval.getStartTime()); 37 } 38 return getEndTime().compareTo(interval.getEndTime()); 39 } 40 41 /** 42 * Interface of the class which holds TimeInterval 43 * 44 * @hide 45 */ 46 public interface TimeIntervalHolder { 47 /** Returns time interval. */ getInterval()48 TimeInterval getInterval(); 49 } 50 51 private final Instant mStartTime; 52 private final Instant mEndTime; 53 TimeInterval(@onNull Instant startTime, @NonNull Instant endTime)54 public TimeInterval(@NonNull Instant startTime, @NonNull Instant endTime) { 55 Objects.requireNonNull(startTime); 56 Objects.requireNonNull(endTime); 57 if (!endTime.isAfter(startTime)) { 58 throw new IllegalArgumentException("End time must be after start time."); 59 } 60 mStartTime = startTime; 61 mEndTime = endTime; 62 } 63 64 /* 65 * Returns start time of the interval. 66 */ 67 @NonNull getStartTime()68 public Instant getStartTime() { 69 return mStartTime; 70 } 71 72 /* 73 * Returns end time of the interval. 74 */ 75 @NonNull getEndTime()76 public Instant getEndTime() { 77 return mEndTime; 78 } 79 80 @Override equals(Object o)81 public boolean equals(Object o) { 82 if (this == o) return true; 83 if (!(o instanceof TimeInterval)) return false; 84 TimeInterval that = (TimeInterval) o; 85 return getStartTime().toEpochMilli() == that.getStartTime().toEpochMilli() 86 && getEndTime().toEpochMilli() == that.getEndTime().toEpochMilli(); 87 } 88 89 @Override hashCode()90 public int hashCode() { 91 return Objects.hash(getStartTime(), getEndTime()); 92 } 93 } 94