2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
24 package org.openecomp.appc.util;
26 import java.sql.Timestamp;
27 import java.text.DateFormat;
28 import java.text.ParseException;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Calendar;
32 import java.util.Date;
33 import java.util.GregorianCalendar;
34 import java.util.List;
35 import java.util.Locale;
36 import java.util.SimpleTimeZone;
37 import java.util.TimeZone;
39 import javax.xml.datatype.DatatypeConfigurationException;
40 import javax.xml.datatype.DatatypeFactory;
41 import javax.xml.datatype.XMLGregorianCalendar;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * This class is a general purpose helper class to augment standard Java time support.
51 public final class Time {
54 * Logger to log operations
56 private static final Logger LOG = LoggerFactory.getLogger(Time.class);
59 * A formatter to be used to format values
61 private static SimpleDateFormat dateformatter = null;
64 * The UTC timezone (for UTC or GMT time)
66 @SuppressWarnings("nls")
67 private static final TimeZone utcTZ = TimeZone.getTimeZone("UTC");
70 * The cached reference to the datatype factory
72 private static DatatypeFactory xmlDatatypeFactory = null;
75 * Private default constructor prevents instantiation
82 * Increments a date by the indicated months, days, hours, minutes, and seconds, and returns the updated date.
85 * The date to be manipulated
87 * The number of months to be added to the date
89 * The number of days to be added to the date
91 * The number of hours to be added to the date
93 * The number of minutes to be added to the date
95 * The number of seconds to be added to the date
96 * @return The updated date.
98 public static Date addTime(final Date date, final int months, final int days, final int hours, final int minutes,
100 Calendar cal = Calendar.getInstance();
102 cal.add(Calendar.MONTH, months);
103 cal.add(Calendar.DATE, days);
104 cal.add(Calendar.HOUR_OF_DAY, hours);
105 cal.add(Calendar.MINUTE, minutes);
106 cal.add(Calendar.SECOND, seconds);
107 return cal.getTime();
111 * Clears the time components of a calendar to zero, leaving the date components unchanged.
114 * the calendar to be updated
115 * @return The updated calendar object
117 public static Calendar dateOnly(final Calendar cal) {
118 cal.set(Calendar.HOUR_OF_DAY, 0);
119 cal.set(Calendar.MINUTE, 0);
120 cal.set(Calendar.SECOND, 0);
121 cal.set(Calendar.MILLISECOND, 0);
126 * This method returns the local time that corresponds to the end of the current day
128 * @return The time that corresponds to the end of the current day, expressed as local time
130 public static Date endOfDayLocal() {
131 return endOfDayLocal(new Date());
135 * This method returns the last moment of the day for the supplied local time. This is defined as the millisecond
136 * before midnight of the current date represented by the local time.
139 * The local time for which the last moment of the day is desired.
140 * @return The millisecond prior to midnight, local time.
142 public static Date endOfDayLocal(final Date localTime) {
144 GregorianCalendar calendar = new GregorianCalendar();
145 calendar.setTime(localTime);
146 calendar.set(Calendar.HOUR, 11);
147 calendar.set(Calendar.AM_PM, Calendar.PM);
148 calendar.set(Calendar.MINUTE, 59);
149 calendar.set(Calendar.SECOND, 59);
150 calendar.set(Calendar.MILLISECOND, 999);
153 return calendar.getTime();
157 * The end of the current day and in the current time zone expressed as a UTC time.
159 * @return The UTC time that corresponds to the end of the current day
161 public static Date endOfDayUTC() {
162 return endOfDayUTC(new Date());
166 * Returns the UTC time that corresponds to the end of the day for the local time specified, using the current
167 * (default) time zone.
170 * The local time for which we are requesting the UTC time that corresponds to the end of the day
171 * @return The UTC time that corresponds to the end of the local day specified by the local time.
173 public static Date endOfDayUTC(final Date localTime) {
174 return endOfDayUTC(localTime, TimeZone.getDefault());
178 * Returns the time expressed in UTC time of the end of the day specified in local time and within the local time
182 * The local time for which we will compute the end of the local day, and then convert to UTC time.
183 * @param localTimeZone
184 * The time zone that the local time is within.
185 * @return The UTC date that corresponds to the end of the day local time and in the local time zone.
187 public static Date endOfDayUTC(final Date localTime, final TimeZone localTimeZone) {
188 Date endOfDay = endOfDayLocal(localTime);
189 return utcDate(endOfDay, localTimeZone);
193 * returns current Date in 'UTC' Timezone
195 * @return The current date, expressed in the UTC timezone.
197 @SuppressWarnings("nls")
198 public static Date getCurrentUTCDate() {
200 // This code incorrectly changes the default timezone for the entire JVM in order to compute the UTC
201 // date for the current time.
203 GregorianCalendar calendar = new GregorianCalendar();
204 calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
205 calendar.setTimeInMillis(utcTime());
206 return calendar.getTime();
210 * This method loads and caches the reference to the XML data type factory object.
212 * @return The XML Data Type Factory object
214 public static DatatypeFactory getDatatypeFactory() {
215 if (xmlDatatypeFactory == null) {
217 xmlDatatypeFactory = DatatypeFactory.newInstance();
218 } catch (DatatypeConfigurationException e) {
219 e.printStackTrace(System.err);
222 return xmlDatatypeFactory;
226 * Gives the date-time String based on given Locale and Timezone
229 * The date to be formatted
231 * The locale that we want to format the value for
233 * The time zone that the date is within
234 * @return The formatted value
236 public static String getDateByLocaleAndTimeZone(final Date date, final Locale locale, final TimeZone timezone) {
237 String strDate = null;
238 DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
239 df.setTimeZone(timezone);
241 strDate = df.format(date);
247 * Returns singleton UTC date formatter.
251 @SuppressWarnings("nls")
252 private static SimpleDateFormat getDateFormatter() {
253 if (dateformatter == null) {
254 dateformatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
255 dateformatter.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
257 return dateformatter;
261 * This method returns the local time that corresponds to a given UTC time in the current time zone.
264 * The UTC time for which we desire the equivalent local time in the current time zone.
265 * @return The local time that is equivalent to the given UTC time for the current time zone
267 public static long localTime(final long utcTime) {
268 return localTime(utcTime, TimeZone.getDefault());
272 * This method can be used to get the local time that corresponds to a specific UTC time.
274 * This method has a problem since the offset can only be determined by having a local time. So, we take the UTC
275 * time and add the raw offset to it to come up with an approximation of the local time. This gives us a local time
276 * that we can use to determine what the offset should be, which is what we actually add to the UTC time to get the
281 * The UTC time for which we want to obtain the equivalent local time
283 * The time zone that we want the local time to be within
284 * @return The local time for the specified time zone and the given UTC time
286 public static long localTime(final long utcTime, final TimeZone localTZ) {
287 int offset = localTZ.getOffset(utcTime + localTZ.getRawOffset());
288 long result = utcTime + offset;
294 * Sets the date components of a calendar to the specified values, leaving the time components unchanged.
297 * The calendar to be updated
301 * The month to be set
304 * @return The updated calendar object
306 public static Calendar setDate(final Calendar cal, final int year, final int month, final int day) {
307 cal.set(Calendar.YEAR, year);
308 cal.set(Calendar.MONTH, month);
309 cal.set(Calendar.DAY_OF_MONTH, day);
314 * Returns the start of the day expressed in local time for the current local time.
316 * @return The start of the day
318 public static Date startOfDayLocal() {
319 return startOfDayLocal(new Date());
323 * This method returns the date that corresponds to the start of the day local time. The date returned represents
324 * midnight of the previous day represented in local time. If the UTC time is desired, use the methods
325 * {@link #startOfDayUTC(Date, TimeZone)}, {@link #startOfDayUTC(Date)}, or {@link #startOfDayUTC()}
328 * The local date that we wish to compute the start of day for.
329 * @return The date that corresponds to the start of the local day
331 public static Date startOfDayLocal(final Date localTime) {
332 GregorianCalendar calendar = new GregorianCalendar();
333 calendar.setTime(localTime);
334 calendar.set(Calendar.HOUR, 0);
335 calendar.set(Calendar.AM_PM, Calendar.AM);
336 calendar.set(Calendar.MINUTE, 0);
337 calendar.set(Calendar.SECOND, 0);
338 calendar.set(Calendar.MILLISECOND, 0);
340 return calendar.getTime();
344 * This method returns the UTC date that corresponds to the start of the local day based on the current time and the
345 * default time zone (the time zone we are running in).
347 * @return The start of the local day expressed as a UTC time.
349 public static Date startOfDayUTC() {
350 return startOfDayUTC(new Date());
354 * This method returns the UTC date that corresponds to the start of the local day specified in the current time
358 * The local time to be used to compute the start of the day
359 * @return The start of the local day expressed as a UTC time.
361 public static Date startOfDayUTC(final Date localTime) {
362 return startOfDayUTC(localTime, TimeZone.getDefault());
366 * This method returns the UTC date that corresponds to the start of the local day specified in the local timezone.
369 * The local time to be used to compute start of day
370 * @param localTimeZone
371 * The time zone that the local time was recorded within
372 * @return The corresponding UTC date
374 public static Date startOfDayUTC(final Date localTime, final TimeZone localTimeZone) {
375 Date startOfDay = startOfDayLocal(localTime);
376 return utcDate(startOfDay, localTimeZone);
380 * This method creates and returns an XML timestamp expressed as the current UTC value for the system. The caller
381 * does not specify the time value or time zone using this method. This ensures that the timestamp value is always
382 * expressed as UTC time.
384 * @return The XMLGregorianCalendar that can be used to record the timestamp
387 public static XMLGregorianCalendar timestamp() {
388 getDatatypeFactory();
389 XMLGregorianCalendar ts = xmlDatatypeFactory.newXMLGregorianCalendar();
390 GregorianCalendar utc = new GregorianCalendar();
391 utc.setTime(utcDate());
393 ts.setYear(utc.get(Calendar.YEAR));
394 // Calendar Months are from 0-11 need to +1
395 ts.setMonth(utc.get(Calendar.MONTH) + 1);
396 ts.setDay(utc.get(Calendar.DAY_OF_MONTH));
397 ts.setHour(utc.get(Calendar.HOUR_OF_DAY));
398 ts.setMinute(utc.get(Calendar.MINUTE));
399 ts.setSecond(utc.get(Calendar.SECOND));
400 ts.setMillisecond(utc.get(Calendar.MILLISECOND));
405 * Converts XMLGregorianCalendar to java.util.Date in Java
408 * the calendar object to be converted
409 * @return The equivalent Date object
411 public static Date toDate(final XMLGregorianCalendar calendar) {
412 if (calendar == null) {
415 return calendar.toGregorianCalendar().getTime();
419 * Converts java Date to XMLGregorianCalendar.
422 * The date to convert
423 * @return The XMLGregorianCalendar for the specified date
425 @SuppressWarnings("nls")
426 public static XMLGregorianCalendar toXMLCalendar(final Date date) {
427 GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
430 XMLGregorianCalendar xmlCal = null;
432 xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
433 } catch (DatatypeConfigurationException e) {
434 LOG.error("toXMLCalendar", e);
440 * Truncates the provided date so that only the date, hours, and minutes portions are significant. This method
441 * returns the date with the seconds and milliseconds forced to zero.
444 * The date to truncate
445 * @return The date with only the year, month, day, hours, and minutes significant.
447 public static Date truncDate(final Date date) {
448 Calendar cal = Calendar.getInstance();
450 cal.set(Calendar.SECOND, 0);
451 cal.set(Calendar.MILLISECOND, 0);
452 return cal.getTime();
456 * The UTC date that corresponds to the current date in the local time zone.
458 * @return The UTC date for now in the current time zone.
460 public static Date utcDate() {
465 * The UTC date for the specified date in the current (default) time zone.
468 * The local date for which the UTC date is desired.
469 * @return The UTC date that corresponds to the date in the current time zone.
471 public static Date utcDate(final Date date) {
472 TimeZone tz = TimeZone.getDefault();
473 return utcDate(date, tz);
477 * Returns the UTC date for the specified date in the specified time zone.
480 * The date for which the UTC date is desired in the specified zone
482 * The time zone that corresponds to the date to be converted to UTC
483 * @return The UTC date that corresponds to the local date in the local time zone.
485 public static Date utcDate(final Date date, final TimeZone tz) {
486 return new Date(utcTime(date.getTime(), tz));
490 * Format incoming date as string in GMT or UTC.
493 * The date to be formatted
494 * @return The date formatted for UTC timezone
496 public static String utcFormat(final Date dt) {
497 String strDate = null;
498 DateFormat df = getDateFormatter();
500 strDate = df.format(dt);
506 * Parse previously formated Date object back to a Date object.
509 * The representation of a UTC date as a string
510 * @return The date object containing the parsed representation, or null if the representation cannot be parsed
512 @SuppressWarnings("nls")
513 public static Date utcParse(final String dateStr) {
517 return utcParse(dateStr, adtl);
521 * Parse previously formated Date object back to a Date object.
524 * The representation of a UTC date as a string
525 * @param adtlFormatStrings
526 * A list of strings that represent additional date format representations to try and parse.
527 * @return The date object containing the parsed representation, or null if the representation cannot be parsed
529 @SuppressWarnings("nls")
530 public static Date utcParse(final String dateStr, String... adtlFormatStrings) {
531 if (dateStr != null) {
532 // Build the list of formatters starting with the default defined in the class
533 List<DateFormat> formats = new ArrayList<>();
534 formats.add(getDateFormatter());
536 if (adtlFormatStrings != null) {
537 for (String s : adtlFormatStrings) {
538 formats.add(new SimpleDateFormat(s));
542 // Return the first matching date formatter's result
543 for (DateFormat df : formats) {
544 df.setTimeZone(utcTZ);
546 return df.parse(dateStr);
547 } catch (ParseException e) {
548 LOG.debug(String.format("IGNORE - Date string [%s] does not fit pattern [%s]", dateStr,
557 * This method returns the current time for the UTC timezone
559 * @return The time in the UTC time zone that corresponds to the current local time.
561 public static long utcTime() {
562 return new Date().getTime();
566 * Get the UTC time that corresponds to the given time in the default time zone (current time zone for the system).
569 * The time in the current time zone for which the UTC time is desired.
570 * @return The UTC time
572 public static long utcTime(final long localTime) {
573 TimeZone tz = TimeZone.getDefault();
574 return utcTime(localTime, tz);
578 * Get the UTC time that corresponds to the given time in the specified timezone.
580 * Note that the java <code>getOffset()</code> method works a little counter-intuitive. It returns the offset that
581 * would be added to the current UTC time to get the LOCAL time represented by the local time zone. That means to
582 * get the UTC time, we need to SUBTRACT this offset from the local time.
586 * The time in the specified time zone for which the UTC time is desired.
588 * The time zone which the local time is in.
589 * @return The UTC time for the specified local time in the specified local time zone.
591 public static long utcTime(final long localTime, final TimeZone localTZ) {
592 int offset = localTZ.getOffset(localTime);
593 return localTime - offset;
598 * Creates a timestamp value from a time
601 * The UTC time to convert to a timestamp
602 * @return The timestamp
604 public static Timestamp utcTimestamp(final long utcTime) {
605 TimeZone tz = TimeZone.getDefault();
606 return new Timestamp(utcTime(utcTime, tz));