2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.sleepiq.internal.api.dto;
15 import java.time.Duration;
16 import java.util.Objects;
17 import java.util.concurrent.TimeUnit;
18 import java.util.regex.Matcher;
19 import java.util.regex.Pattern;
22 * The {@link TimeSince} converts from "nn d hh:mm:ss" to Duration
24 * @author Gregory Moyer - Initial contribution
26 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() {
36 public void setDuration(Duration duration) {
37 this.duration = duration == null ? null : duration.abs();
40 public TimeSince withDuration(long days, long hours, long minutes, long seconds) {
41 return withDuration(Duration.ofSeconds(TimeUnit.DAYS.toSeconds(days) + TimeUnit.HOURS.toSeconds(hours)
42 + TimeUnit.MINUTES.toSeconds(minutes) + seconds));
45 public TimeSince withDuration(Duration duration) {
46 setDuration(duration);
51 public int hashCode() {
54 result = prime * result + ((duration == null) ? 0 : duration.hashCode());
59 public boolean equals(Object obj) {
66 if (!(obj instanceof TimeSince)) {
69 TimeSince other = (TimeSince) obj;
70 if (duration == null) {
71 if (other.duration != null) {
74 } else if (!duration.equals(other.duration)) {
81 public String toString() {
82 long totalDays = duration.toDays();
83 long totalHours = duration.toHours();
84 long totalMinutes = duration.toMinutes();
85 long totalSeconds = duration.getSeconds();
87 long hours = totalHours - TimeUnit.DAYS.toHours(totalDays);
88 long minutes = totalMinutes - TimeUnit.HOURS.toMinutes(totalHours);
89 long seconds = totalSeconds - TimeUnit.MINUTES.toSeconds(totalMinutes);
92 return String.format("%d d %02d:%02d:%02d", totalDays, hours, minutes, seconds);
95 return String.format("%02d:%02d:%02d", hours, minutes, seconds);
98 public static TimeSince parse(CharSequence text) {
99 Objects.requireNonNull(text, "text");
101 Matcher matcher = PATTERN.matcher(text);
102 if (!matcher.matches()) {
103 return new TimeSince().withDuration(Duration.ZERO);
106 String dayMatch = matcher.group(2);
107 String hourMatch = matcher.group(3);
108 String minuteMatch = matcher.group(4);
109 String secondMatch = matcher.group(5);
111 StringBuilder sb = new StringBuilder("P");
112 if (dayMatch != null) {
113 sb.append(dayMatch).append('D');
115 sb.append('T').append(hourMatch).append('H').append(minuteMatch).append('M').append(secondMatch).append('S');
117 return new TimeSince().withDuration(Duration.parse(sb.toString()));