Imported Upstream version 3.8.0
[platform/upstream/protobuf.git] / java / util / src / main / java / com / google / protobuf / util / TimeUtil.java
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 package com.google.protobuf.util;
32
33 import com.google.protobuf.Duration;
34 import com.google.protobuf.Timestamp;
35
36 import java.math.BigInteger;
37 import java.text.ParseException;
38
39 /**
40  * Utilities to help create/manipulate Timestamp/Duration
41  *
42  * @deprecated Use {@link Durations} and {@link Timestamps} instead.
43  */
44 @Deprecated
45 public final class TimeUtil {
46   // Timestamp for "0001-01-01T00:00:00Z"
47   public static final long TIMESTAMP_SECONDS_MIN = -62135596800L;
48
49   // Timestamp for "9999-12-31T23:59:59Z"
50   public static final long TIMESTAMP_SECONDS_MAX = 253402300799L;
51   public static final long DURATION_SECONDS_MIN = -315576000000L;
52   public static final long DURATION_SECONDS_MAX = 315576000000L;
53
54   private static final long NANOS_PER_SECOND = 1000000000;
55
56   private TimeUtil() {}
57
58   /**
59    * Convert Timestamp to RFC 3339 date string format. The output will always
60    * be Z-normalized and uses 3, 6 or 9 fractional digits as required to
61    * represent the exact value. Note that Timestamp can only represent time
62    * from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. See
63    * https://www.ietf.org/rfc/rfc3339.txt
64    *
65    * <p>Example of generated format: "1972-01-01T10:00:20.021Z"
66    *
67    * @return The string representation of the given timestamp.
68    * @throws IllegalArgumentException if the given timestamp is not in the
69    *         valid range.
70    * @deprecated Use {@link Timestamps#toString} instead.
71    */
72   @Deprecated
73   public static String toString(Timestamp timestamp) {
74     return Timestamps.toString(timestamp);
75   }
76
77   /**
78    * Parse from RFC 3339 date string to Timestamp. This method accepts all
79    * outputs of {@link #toString(Timestamp)} and it also accepts any fractional
80    * digits (or none) and any offset as long as they fit into nano-seconds
81    * precision.
82    *
83    * <p>Example of accepted format: "1972-01-01T10:00:20.021-05:00"
84    *
85    * @return A Timestamp parsed from the string.
86    * @throws ParseException if parsing fails.
87    * @deprecated Use {@link Timestamps#parse} instead.
88    */
89   @Deprecated
90   public static Timestamp parseTimestamp(String value) throws ParseException {
91     return Timestamps.parse(value);
92   }
93
94   /**
95    * Convert Duration to string format. The string format will contains 3, 6,
96    * or 9 fractional digits depending on the precision required to represent
97    * the exact Duration value. For example: "1s", "1.010s", "1.000000100s",
98    * "-3.100s" The range that can be represented by Duration is from
99    * -315,576,000,000 to +315,576,000,000 inclusive (in seconds).
100    *
101    * @return The string representation of the given duration.
102    * @throws IllegalArgumentException if the given duration is not in the valid
103    *         range.
104    * @deprecated Use {@link Durations#toString} instead.
105    */
106   @Deprecated
107   public static String toString(Duration duration) {
108     return Durations.toString(duration);
109   }
110
111   /**
112    * Parse from a string to produce a duration.
113    *
114    * @return A Duration parsed from the string.
115    * @throws ParseException if parsing fails.
116    * @deprecated Use {@link Durations#parse} instead.
117    */
118   @Deprecated
119   public static Duration parseDuration(String value) throws ParseException {
120     return Durations.parse(value);
121   }
122
123   /**
124    * Create a Timestamp from the number of milliseconds elapsed from the epoch.
125    *
126    * @deprecated Use {@link Timestamps#fromMillis} instead.
127    */
128   @Deprecated
129   public static Timestamp createTimestampFromMillis(long milliseconds) {
130     return Timestamps.fromMillis(milliseconds);
131   }
132
133   /**
134    * Create a Duration from the number of milliseconds.
135    *
136    * @deprecated Use {@link Durations#fromMillis} instead.
137    */
138   @Deprecated
139   public static Duration createDurationFromMillis(long milliseconds) {
140     return Durations.fromMillis(milliseconds);
141   }
142
143   /**
144    * Convert a Timestamp to the number of milliseconds elapsed from the epoch.
145    *
146    * <p>The result will be rounded down to the nearest millisecond. E.g., if the
147    * timestamp represents "1969-12-31T23:59:59.999999999Z", it will be rounded
148    * to -1 millisecond.
149    *
150    * @deprecated Use {@link Timestamps#toMillis} instead.
151    */
152   @Deprecated
153   public static long toMillis(Timestamp timestamp) {
154     return Timestamps.toMillis(timestamp);
155   }
156
157   /**
158    * Convert a Duration to the number of milliseconds.The result will be
159    * rounded towards 0 to the nearest millisecond. E.g., if the duration
160    * represents -1 nanosecond, it will be rounded to 0.
161    *
162    * @deprecated Use {@link Durations#toMillis} instead.
163    */
164   @Deprecated
165   public static long toMillis(Duration duration) {
166     return Durations.toMillis(duration);
167   }
168
169   /**
170    * Create a Timestamp from the number of microseconds elapsed from the epoch.
171    *
172    * @deprecated Use {@link Timestamps#fromMicros} instead.
173    */
174   @Deprecated
175   public static Timestamp createTimestampFromMicros(long microseconds) {
176     return Timestamps.fromMicros(microseconds);
177   }
178
179   /**
180    * Create a Duration from the number of microseconds.
181    *
182    * @deprecated Use {@link Durations#fromMicros} instead.
183    */
184   @Deprecated
185   public static Duration createDurationFromMicros(long microseconds) {
186     return Durations.fromMicros(microseconds);
187   }
188
189   /**
190    * Convert a Timestamp to the number of microseconds elapsed from the epoch.
191    *
192    * <p>The result will be rounded down to the nearest microsecond. E.g., if the
193    * timestamp represents "1969-12-31T23:59:59.999999999Z", it will be rounded
194    * to -1 millisecond.
195    *
196    * @deprecated Use {@link Timestamps#toMicros} instead.
197    */
198   @Deprecated
199   public static long toMicros(Timestamp timestamp) {
200     return Timestamps.toMicros(timestamp);
201   }
202
203   /**
204    * Convert a Duration to the number of microseconds.The result will be
205    * rounded towards 0 to the nearest microseconds. E.g., if the duration
206    * represents -1 nanosecond, it will be rounded to 0.
207    *
208    * @deprecated Use {@link Durations#toMicros} instead.
209    */
210   @Deprecated
211   public static long toMicros(Duration duration) {
212     return Durations.toMicros(duration);
213   }
214
215   /**
216    * Create a Timestamp from the number of nanoseconds elapsed from the epoch.
217    *
218    * @deprecated Use {@link Timestamps#fromNanos} instead.
219    */
220   @Deprecated
221   public static Timestamp createTimestampFromNanos(long nanoseconds) {
222     return Timestamps.fromNanos(nanoseconds);
223   }
224
225   /**
226    * Create a Duration from the number of nanoseconds.
227    *
228    * @deprecated Use {@link Durations#fromNanos} instead.
229    */
230   @Deprecated
231   public static Duration createDurationFromNanos(long nanoseconds) {
232     return Durations.fromNanos(nanoseconds);
233   }
234
235   /**
236    * Convert a Timestamp to the number of nanoseconds elapsed from the epoch.
237    *
238    * @deprecated Use {@link Timestamps#toNanos} instead.
239    */
240   @Deprecated
241   public static long toNanos(Timestamp timestamp) {
242     return Timestamps.toNanos(timestamp);
243   }
244
245   /**
246    * Convert a Duration to the number of nanoseconds.
247    *
248    * @deprecated Use {@link Durations#toNanos} instead.
249    */
250   @Deprecated
251   public static long toNanos(Duration duration) {
252     return Durations.toNanos(duration);
253   }
254
255   /**
256    * Get the current time.
257    *
258    * @deprecated Use {@code Timestamps.fromMillis(System.currentTimeMillis())} instead.
259    */
260   @Deprecated
261   public static Timestamp getCurrentTime() {
262     return Timestamps.fromMillis(System.currentTimeMillis());
263   }
264
265   /**
266    * Get the epoch.
267    *
268    * @deprecated Use {@code Timestamps.fromMillis(0)} instead.
269    */
270   @Deprecated
271   public static Timestamp getEpoch() {
272     return Timestamp.getDefaultInstance();
273   }
274
275   /**
276    * Calculate the difference between two timestamps.
277    *
278    * @deprecated Use {@link Timestamps#between} instead.
279    */
280   @Deprecated
281   public static Duration distance(Timestamp from, Timestamp to) {
282     return Timestamps.between(from, to);
283   }
284
285   /**
286    * Add a duration to a timestamp.
287    *
288    * @deprecated Use {@link Timestamps#add} instead.
289    */
290   @Deprecated
291   public static Timestamp add(Timestamp start, Duration length) {
292     return Timestamps.add(start, length);
293   }
294
295   /**
296    * Subtract a duration from a timestamp.
297    *
298    * @deprecated Use {@link Timestamps#subtract} instead.
299    */
300   @Deprecated
301   public static Timestamp subtract(Timestamp start, Duration length) {
302     return Timestamps.subtract(start, length);
303   }
304
305   /**
306    * Add two durations.
307    *
308    * @deprecated Use {@link Durations#add} instead.
309    */
310   @Deprecated
311   public static Duration add(Duration d1, Duration d2) {
312     return Durations.add(d1, d2);
313   }
314
315   /**
316    * Subtract a duration from another.
317    *
318    * @deprecated Use {@link Durations#subtract} instead.
319    */
320   @Deprecated
321   public static Duration subtract(Duration d1, Duration d2) {
322     return Durations.subtract(d1, d2);
323   }
324
325   // Multiplications and divisions.
326
327   // TODO(kak): Delete this.
328   @SuppressWarnings("DurationSecondsToDouble")
329   public static Duration multiply(Duration duration, double times) {
330     double result = duration.getSeconds() * times + duration.getNanos() * times / 1000000000.0;
331     if (result < Long.MIN_VALUE || result > Long.MAX_VALUE) {
332       throw new IllegalArgumentException("Result is out of valid range.");
333     }
334     long seconds = (long) result;
335     int nanos = (int) ((result - seconds) * 1000000000);
336     return normalizedDuration(seconds, nanos);
337   }
338
339   // TODO(kak): Delete this.
340   public static Duration divide(Duration duration, double value) {
341     return multiply(duration, 1.0 / value);
342   }
343
344   // TODO(kak): Delete this.
345   public static Duration multiply(Duration duration, long times) {
346     return createDurationFromBigInteger(toBigInteger(duration).multiply(toBigInteger(times)));
347   }
348
349   // TODO(kak): Delete this.
350   public static Duration divide(Duration duration, long times) {
351     return createDurationFromBigInteger(toBigInteger(duration).divide(toBigInteger(times)));
352   }
353
354   // TODO(kak): Delete this.
355   public static long divide(Duration d1, Duration d2) {
356     return toBigInteger(d1).divide(toBigInteger(d2)).longValue();
357   }
358
359   // TODO(kak): Delete this.
360   public static Duration remainder(Duration d1, Duration d2) {
361     return createDurationFromBigInteger(toBigInteger(d1).remainder(toBigInteger(d2)));
362   }
363
364   private static final BigInteger NANOS_PER_SECOND_BIG_INTEGER =
365       new BigInteger(String.valueOf(NANOS_PER_SECOND));
366
367   private static BigInteger toBigInteger(Duration duration) {
368     return toBigInteger(duration.getSeconds())
369         .multiply(NANOS_PER_SECOND_BIG_INTEGER)
370         .add(toBigInteger(duration.getNanos()));
371   }
372
373   private static BigInteger toBigInteger(long value) {
374     return new BigInteger(String.valueOf(value));
375   }
376
377   private static Duration createDurationFromBigInteger(BigInteger value) {
378     long seconds = value.divide(new BigInteger(String.valueOf(NANOS_PER_SECOND))).longValue();
379     int nanos = value.remainder(new BigInteger(String.valueOf(NANOS_PER_SECOND))).intValue();
380     return normalizedDuration(seconds, nanos);
381   }
382
383   private static Duration normalizedDuration(long seconds, int nanos) {
384     if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
385       seconds += nanos / NANOS_PER_SECOND;
386       nanos %= NANOS_PER_SECOND;
387     }
388     if (seconds > 0 && nanos < 0) {
389       nanos += NANOS_PER_SECOND;
390       seconds -= 1;
391     }
392     if (seconds < 0 && nanos > 0) {
393       nanos -= NANOS_PER_SECOND;
394       seconds += 1;
395     }
396     if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) {
397       throw new IllegalArgumentException("Duration is out of valid range.");
398     }
399     return Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build();
400   }
401 }