1 /* Copyright 2002-2018 CS Systèmes d'Information
2 * Licensed to CS Systèmes d'Information (CS) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * CS licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.orekit.time;
18
19 import java.io.Serializable;
20 import java.text.DecimalFormat;
21 import java.text.DecimalFormatSymbols;
22 import java.util.Locale;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25
26 import org.hipparchus.util.FastMath;
27 import org.orekit.errors.OrekitIllegalArgumentException;
28 import org.orekit.errors.OrekitMessages;
29
30
31 /** Class representing a time within the day broken up as hour,
32 * minute and second components.
33 * <p>Instances of this class are guaranteed to be immutable.</p>
34 * @see DateComponents
35 * @see DateTimeComponents
36 * @author Luc Maisonobe
37 */
38 public class TimeComponents implements Serializable, Comparable<TimeComponents> {
39
40 /** Constant for commonly used hour 00:00:00. */
41 public static final TimeComponents H00 = new TimeComponents(0, 0, 0);
42
43 /** Constant for commonly used hour 12:00:00. */
44 public static final TimeComponents H12 = new TimeComponents(12, 0, 0);
45
46 /** Serializable UID. */
47 private static final long serialVersionUID = 20160331L;
48
49 /** Format for hours and minutes. */
50 private static final DecimalFormat TWO_DIGITS = new DecimalFormat("00");
51
52 /** Format for seconds. */
53 private static final DecimalFormat SECONDS_FORMAT =
54 new DecimalFormat("00.000", new DecimalFormatSymbols(Locale.US));
55
56 /** Basic and extends formats for local time, with optional timezone. */
57 private static Pattern ISO8601_FORMATS = Pattern.compile("^(\\d\\d):?(\\d\\d):?(\\d\\d(?:[.,]\\d+)?)?(?:Z|([-+]\\d\\d(?::?\\d\\d)?))?$");
58
59 /** Hour number. */
60 private final int hour;
61
62 /** Minute number. */
63 private final int minute;
64
65 /** Second number. */
66 private final double second;
67
68 /** Offset between the specified date and UTC.
69 * <p>
70 * Always an integral number of minutes, as per ISO-8601 standard.
71 * </p>
72 * @since 7.2
73 */
74 private final int minutesFromUTC;
75
76 /** Build a time from its clock elements.
77 * <p>Note that seconds between 60.0 (inclusive) and 61.0 (exclusive) are allowed
78 * in this method, since they do occur during leap seconds introduction
79 * in the {@link UTCScale UTC} time scale.</p>
80 * @param hour hour number from 0 to 23
81 * @param minute minute number from 0 to 59
82 * @param second second number from 0.0 to 61.0 (excluded)
83 * @exception IllegalArgumentException if inconsistent arguments
84 * are given (parameters out of range)
85 */
86 public TimeComponents(final int hour, final int minute, final double second)
87 throws IllegalArgumentException {
88 this(hour, minute, second, 0);
89 }
90
91 /** Build a time from its clock elements.
92 * <p>Note that seconds between 60.0 (inclusive) and 61.0 (exclusive) are allowed
93 * in this method, since they do occur during leap seconds introduction
94 * in the {@link UTCScale UTC} time scale.</p>
95 * @param hour hour number from 0 to 23
96 * @param minute minute number from 0 to 59
97 * @param second second number from 0.0 to 61.0 (excluded)
98 * @param minutesFromUTC offset between the specified date and UTC, as an
99 * integral number of minutes, as per ISO-8601 standard
100 * @exception IllegalArgumentException if inconsistent arguments
101 * are given (parameters out of range)
102 * @since 7.2
103 */
104 public TimeComponents(final int hour, final int minute, final double second,
105 final int minutesFromUTC)
106 throws IllegalArgumentException {
107
108 // range check
109 if ((hour < 0) || (hour > 23) ||
110 (minute < 0) || (minute > 59) ||
111 (second < 0) || (second >= 61.0)) {
112 throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_HMS_TIME,
113 hour, minute, second);
114 }
115
116 this.hour = hour;
117 this.minute = minute;
118 this.second = second;
119 this.minutesFromUTC = minutesFromUTC;
120
121 }
122
123 /** Build a time from the second number within the day.
124 * <p>
125 * This constructor is always in UTC (i.e. {@link #getMinutesFromUTC() will return 0}).
126 * </p>
127 * @param secondInDay second number from 0.0 to {@link
128 * org.orekit.utils.Constants#JULIAN_DAY} (excluded)
129 * @exception OrekitIllegalArgumentException if seconds number is out of range
130 */
131 public TimeComponents(final double secondInDay)
132 throws OrekitIllegalArgumentException {
133 this(0, secondInDay);
134 }
135
136 /** Build a time from the second number within the day.
137 * <p>
138 * The second number is defined here as the sum
139 * {@code secondInDayA + secondInDayB} from 0.0 to {@link
140 * org.orekit.utils.Constants#JULIAN_DAY} (excluded). The two parameters
141 * are used for increased accuracy.
142 * </p>
143 * <p>
144 * This constructor is always in UTC (i.e. {@link #getMinutesFromUTC() will return 0}).
145 * </p>
146 * @param secondInDayA first part of the second number
147 * @param secondInDayB last part of the second number
148 * @exception OrekitIllegalArgumentException if seconds number is out of range
149 */
150 public TimeComponents(final int secondInDayA, final double secondInDayB)
151 throws OrekitIllegalArgumentException {
152
153 // split the numbers as a whole number of seconds
154 // and a fractional part between 0.0 (included) and 1.0 (excluded)
155 final int carry = (int) FastMath.floor(secondInDayB);
156 int wholeSeconds = secondInDayA + carry;
157 final double fractional = secondInDayB - carry;
158
159 // range check
160 if (wholeSeconds < 0 || wholeSeconds > 86400) {
161 // beware, 86400 must be allowed to cope with leap seconds introduction days
162 throw new OrekitIllegalArgumentException(OrekitMessages.OUT_OF_RANGE_SECONDS_NUMBER,
163 wholeSeconds + fractional);
164 }
165
166 // extract the time components
167 hour = wholeSeconds / 3600;
168 wholeSeconds -= 3600 * hour;
169 minute = wholeSeconds / 60;
170 wholeSeconds -= 60 * minute;
171 second = wholeSeconds + fractional;
172 minutesFromUTC = 0;
173
174 }
175
176 /** Parse a string in ISO-8601 format to build a time.
177 * <p>The supported formats are:
178 * <ul>
179 * <li>basic and extended format local time: hhmmss, hh:mm:ss (with optional decimals in seconds)</li>
180 * <li>optional UTC time: hhmmssZ, hh:mm:ssZ</li>
181 * <li>optional signed hours UTC offset: hhmmss+HH, hhmmss-HH, hh:mm:ss+HH, hh:mm:ss-HH</li>
182 * <li>optional signed basic hours and minutes UTC offset: hhmmss+HHMM, hhmmss-HHMM, hh:mm:ss+HHMM, hh:mm:ss-HHMM</li>
183 * <li>optional signed extended hours and minutes UTC offset: hhmmss+HH:MM, hhmmss-HH:MM, hh:mm:ss+HH:MM, hh:mm:ss-HH:MM</li>
184 * </ul>
185 *
186 * <p> As shown by the list above, only the complete representations defined in section 4.2
187 * of ISO-8601 standard are supported, neither expended representations nor representations
188 * with reduced accuracy are supported.
189 *
190 * @param string string to parse
191 * @return a parsed time
192 * @exception IllegalArgumentException if string cannot be parsed
193 */
194 public static TimeComponents parseTime(final String string) {
195
196 // is the date a calendar date ?
197 final Matcher timeMatcher = ISO8601_FORMATS.matcher(string);
198 if (timeMatcher.matches()) {
199 final int hour = Integer.parseInt(timeMatcher.group(1));
200 final int minute = Integer.parseInt(timeMatcher.group(2));
201 final double second = timeMatcher.group(3) == null ? 0.0 : Double.parseDouble(timeMatcher.group(3).replace(',', '.'));
202 final String offset = timeMatcher.group(4);
203 final int minutesFromUTC;
204 if (offset == null) {
205 // no offset from UTC is given
206 minutesFromUTC = 0;
207 } else {
208 // we need to parse an offset from UTC
209 // the sign is mandatory and the ':' separator is optional
210 // so we can have offsets given as -06:00 or +0100
211 final int sign = offset.codePointAt(0) == '-' ? -1 : +1;
212 final int hourOffset = Integer.parseInt(offset.substring(1, 3));
213 final int minutesOffset = offset.length() <= 3 ? 0 : Integer.parseInt(offset.substring(offset.length() - 2));
214 minutesFromUTC = sign * (minutesOffset + 60 * hourOffset);
215 }
216 return new TimeComponents(hour, minute, second, minutesFromUTC);
217 }
218
219 throw new OrekitIllegalArgumentException(OrekitMessages.NON_EXISTENT_TIME, string);
220
221 }
222
223 /** Get the hour number.
224 * @return hour number from 0 to 23
225 */
226 public int getHour() {
227 return hour;
228 }
229
230 /** Get the minute number.
231 * @return minute minute number from 0 to 59
232 */
233 public int getMinute() {
234 return minute;
235 }
236
237 /** Get the seconds number.
238 * @return second second number from 0.0 to 60.0 (excluded)
239 */
240 public double getSecond() {
241 return second;
242 }
243
244 /** Get the offset between the specified date and UTC.
245 * <p>
246 * The offset is always an integral number of minutes, as per ISO-8601 standard.
247 * </p>
248 * @return offset in minutes between the specified date and UTC
249 * @since 7.2
250 */
251 public int getMinutesFromUTC() {
252 return minutesFromUTC;
253 }
254
255 /** Get the second number within the local day, <em>without</em> applying the {@link #getMinutesFromUTC() offset from UTC}.
256 * @return second number from 0.0 to Constants.JULIAN_DAY
257 * @see #getSecondsInUTCDay()
258 * @since 7.2
259 */
260 public double getSecondsInLocalDay() {
261 return second + 60 * minute + 3600 * hour;
262 }
263
264 /** Get the second number within the UTC day, applying the {@link #getMinutesFromUTC() offset from UTC}.
265 * @return second number from {@link #getMinutesFromUTC() -getMinutesFromUTC()}
266 * to Constants.JULIAN_DAY {@link #getMinutesFromUTC() + getMinutesFromUTC()}
267 * @see #getSecondsInLocalDay()
268 * @since 7.2
269 */
270 public double getSecondsInUTCDay() {
271 return second + 60 * (minute - minutesFromUTC) + 3600 * hour;
272 }
273
274 /** Get a string representation of the time.
275 * @return string representation of the time
276 */
277 public String toString() {
278 StringBuilder builder = new StringBuilder().
279 append(TWO_DIGITS.format(hour)).append(':').
280 append(TWO_DIGITS.format(minute)).append(':').
281 append(SECONDS_FORMAT.format(second));
282 if (minutesFromUTC != 0) {
283 builder = builder.
284 append(minutesFromUTC < 0 ? '-' : '+').
285 append(TWO_DIGITS.format(FastMath.abs(minutesFromUTC) / 60)).append(':').
286 append(TWO_DIGITS.format(FastMath.abs(minutesFromUTC) % 60));
287 }
288 return builder.toString();
289 }
290
291 /** {@inheritDoc} */
292 public int compareTo(final TimeComponents other) {
293 return Double.compare(getSecondsInUTCDay(), other.getSecondsInUTCDay());
294 }
295
296 /** {@inheritDoc} */
297 public boolean equals(final Object other) {
298 try {
299 final TimeComponents otherTime = (TimeComponents) other;
300 return otherTime != null &&
301 hour == otherTime.hour &&
302 minute == otherTime.minute &&
303 second == otherTime.second &&
304 minutesFromUTC == otherTime.minutesFromUTC;
305 } catch (ClassCastException cce) {
306 return false;
307 }
308 }
309
310 /** {@inheritDoc} */
311 public int hashCode() {
312 final long bits = Double.doubleToLongBits(second);
313 return ((hour << 16) ^ ((minute - minutesFromUTC) << 8)) ^ (int) (bits ^ (bits >>> 32));
314 }
315
316 }