2 * Copyright 2017 Gregory Moyer
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.openhab.binding.sleepiq.api.model;
18 import java.time.Duration;
19 import java.time.format.DateTimeParseException;
20 import java.util.Objects;
21 import java.util.concurrent.TimeUnit;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
25 public class TimeSince
27 private static final Pattern PATTERN = Pattern.compile("(([0-9]+) d )?([0-9]{2}):([0-9]{2}):([0-9]{2})",
28 Pattern.CASE_INSENSITIVE);
30 private Duration duration;
32 public Duration getDuration()
37 public void setDuration(Duration duration)
39 this.duration = duration == null ? null : duration.abs();
42 public TimeSince withDuration(long days, long hours, long minutes, long seconds)
44 return withDuration(Duration.ofSeconds(TimeUnit.DAYS.toSeconds(days)
45 + TimeUnit.HOURS.toSeconds(hours)
46 + TimeUnit.MINUTES.toSeconds(minutes)
50 public TimeSince withDuration(Duration duration)
52 setDuration(duration);
61 result = prime * result + ((duration == null) ? 0 : duration.hashCode());
66 public boolean equals(Object obj)
76 if (!(obj instanceof TimeSince))
80 TimeSince other = (TimeSince)obj;
83 if (other.duration != null)
88 else if (!duration.equals(other.duration))
96 public String toString()
98 long totalDays = duration.toDays();
99 long totalHours = duration.toHours();
100 long totalMinutes = duration.toMinutes();
101 long totalSeconds = duration.getSeconds();
103 long hours = totalHours - TimeUnit.DAYS.toHours(totalDays);
104 long minutes = totalMinutes - TimeUnit.HOURS.toMinutes(totalHours);
105 long seconds = totalSeconds - TimeUnit.MINUTES.toSeconds(totalMinutes);
109 return String.format("%d d %02d:%02d:%02d", totalDays, hours, minutes, seconds);
112 return String.format("%02d:%02d:%02d", hours, minutes, seconds);
115 public static TimeSince parse(CharSequence text)
117 Objects.requireNonNull(text, "text");
119 Matcher matcher = PATTERN.matcher(text);
120 if (!matcher.matches())
122 throw new DateTimeParseException("Text cannot be parsed", text, 0);
125 String dayMatch = matcher.group(2);
126 String hourMatch = matcher.group(3);
127 String minuteMatch = matcher.group(4);
128 String secondMatch = matcher.group(5);
130 StringBuilder sb = new StringBuilder("P");
131 if (dayMatch != null)
133 sb.append(dayMatch).append('D');
143 return new TimeSince().withDuration(Duration.parse(sb.toString()));