eriezelagera

jutils - Times

Oct 12th, 2016
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 41.38 KB | None | 0 0
  1. package my.jutils;
  2.  
  3. import java.math.*;
  4. import java.text.*;
  5. import java.util.*;
  6. import java.util.concurrent.TimeUnit;
  7. import org.joda.time.*;
  8. import org.joda.time.format.*;
  9. import org.slf4j.*;
  10.  
  11. /**
  12.  * Utility for Date and Time processing.
  13.  * <p>
  14.  * We've use Joda-Time framework on some methods under this utility.
  15.  *
  16.  * @author Erieze and Einar Lagera
  17.  */
  18. public class Times {
  19.  
  20.     private static final Logger LOGGER = LoggerFactory.getLogger(Times.class);
  21.     /**
  22.      * {@link DateTimeZone} instance for {@code Manila}.
  23.      */
  24.     public static final DateTimeZone MANILA_TIMEZONE = DateTimeZone.forID("Asia/Manila");
  25.  
  26.     /**
  27.      * Gets the integer time from the current date.
  28.      * <p>
  29.      * Example: Date is <i>19921023 12:30:00</i>, it will get first the
  30.      * <u>12:30</u> from the time and then replaces all the non-digit value into
  31.      * blank to extract the number only which will be <b>1230</b>.
  32.      *
  33.      * @return Exact time in type of {@code int} without non-digit character
  34.      */
  35.     public static int getTime() {
  36.         return Numbers.get(toDateFormat(new Date(), "HH:mm").replaceAll("\\D", ""));
  37.     }
  38.  
  39.     /**
  40.      * Gets the integer time from date.
  41.      * <p>
  42.      * Example: Date is <i>19921023 12:30:00</i>, it will get first the
  43.      * <u>12:30</u> from the time and then replaces all the non-digit value into
  44.      * blank to extract the number only which will be <b>1230</b>.
  45.      *
  46.      * @param date A {@link Date}
  47.      * @return Exact time in type of {@code int} without non-digit character
  48.      */
  49.     public static int getTime(Date date) {
  50.         if (Is.nil(date)) {
  51.             LOGGER.info("Invalid date value!");
  52.             return 0;
  53.         }
  54.         return Numbers.get(toDateFormat(date, "HH:mm").replaceAll("\\D", ""));
  55.     }
  56.  
  57.     /**
  58.      * Converts the {@link String} formatted {@code time} to type of
  59.      * {@code int}.
  60.      * <p>
  61.      * The time should be 24-hour format or you may not get the correct hour of
  62.      * day. Example: <code><i>12:30 -&gt; 1230</i></code>
  63.      *
  64.      * @param time A 24-hour time format in type of {@link String}
  65.      * @return Exact time in type of {@code int} without non-digit character
  66.      */
  67.     public static int toTime(String time) {
  68.         return Numbers.get(time.replaceAll("\\D", ""));
  69.     }
  70.  
  71.     /**
  72.      * Evaluate value if {@code Date} is null.
  73.      * <p>
  74.      * If value is null, then the default value will be used.
  75.      *
  76.      * @param val Value of {@link Date}
  77.      * @param dflt Default value
  78.      * @return {@code dflt} if equal to {@code null}, otherwise {@code val}
  79.      */
  80.     public static Date get(Date val, Date dflt) {
  81.         if (Is.nil(val)) {
  82.             LOGGER.debug("val is null - Returning dflt value ({})", dflt);
  83.             return dflt;
  84.         }
  85.         return val;
  86.     }
  87.  
  88.     /**
  89.      * Evaluate value if {@code Date} is null.
  90.      * <p>
  91.      * If value is null, then the default value will be used.
  92.      *
  93.      * @param val Value of {@link Date}
  94.      * @param dflt Default value
  95.      * @return {@code dflt} if not instance of {@link Date} or equal to
  96.      * {@code null}, otherwise {@code val}
  97.      */
  98.     public static Date get(Object val, Date dflt) {
  99.         if (Is.nil(val)) {
  100.             LOGGER.debug("val is null - Returning dflt value ({})", dflt);
  101.             return dflt;
  102.         }
  103.         if (val instanceof Date) {
  104.             return (Date) val;
  105.         } else {
  106.             LOGGER.info("val is not instance of Date - Returning dflt value ({})", dflt);
  107.             return dflt;
  108.         }
  109.     }
  110.  
  111.     /**
  112.      * Safely copies {@link Date} to have protected mutable passing of
  113.      * reference.
  114.      *
  115.      * @param date A {@link Date}
  116.      * @return Cloned {@code date}
  117.      */
  118.     public static Date newDate(Date date) {
  119.         return Is.nil(date) ? null : new Date(date.getTime());
  120.     }
  121.  
  122.     /**
  123.      * Gets the very start time of the current date.
  124.      *
  125.      * @return The very start time of the date today
  126.      */
  127.     public static Date getStartOf() {
  128.         return new DateTime().withZone(MANILA_TIMEZONE).
  129.                 withHourOfDay(0).
  130.                 withMinuteOfHour(0).
  131.                 withSecondOfMinute(0).toDate();
  132.     }
  133.  
  134.     /**
  135.      * Gets the very start time of the given {@link Date}.
  136.      * <p>
  137.      * If null, it will use the current date.
  138.      * </p>
  139.      *
  140.      * @param date A {@link Date}
  141.      * @return The very start time of {@link Date}
  142.      */
  143.     public static Date getStartOf(Date date) {
  144.         return new DateTime(get(date, new Date())).
  145.                 withHourOfDay(0).
  146.                 withMinuteOfHour(0).
  147.                 withSecondOfMinute(0).toDate();
  148.     }
  149.  
  150.     /**
  151.      * Gets the very start time of the given {@link DateTime}.
  152.      * <p>
  153.      * If null, it will use the current date.
  154.      * </p>
  155.      *
  156.      * @param date A {@link DateTime}
  157.      * @return The very start time of {@link DateTime}
  158.      */
  159.     public static Date getStartOf(DateTime date) {
  160.         if (Is.nil(date)) {
  161.             return getStartOf(new Date());
  162.         }
  163.         return date.
  164.                 withHourOfDay(0).
  165.                 withMinuteOfHour(0).
  166.                 withSecondOfMinute(0).toDate();
  167.     }
  168.  
  169.     /**
  170.      * Gets the end time of the current date.
  171.      *
  172.      * @return The end time of the current date.
  173.      */
  174.     public static Date getEndOf() {
  175.         return new DateTime().withZone(MANILA_TIMEZONE).
  176.                 withHourOfDay(23).
  177.                 withMinuteOfHour(59).
  178.                 withSecondOfMinute(59).toDate();
  179.     }
  180.  
  181.     /**
  182.      * Gets the end time of the given {@link Date}.
  183.      * <p>
  184.      * If null, it will use the current date.
  185.      *
  186.      * @param date A {@link Date}
  187.      * @return The end time of {@link Date}
  188.      */
  189.     public static Date getEndOf(Date date) {
  190.         return new DateTime(get(date, new Date())).
  191.                 withHourOfDay(23).
  192.                 withMinuteOfHour(59).
  193.                 withSecondOfMinute(59).toDate();
  194.     }
  195.  
  196.     /**
  197.      * Gets the end time of the given {@link DateTime}.
  198.      * <p>
  199.      * If null, it will use the current date.
  200.      *
  201.      * @param date A {@link DateTime}
  202.      * @return The end time of {@link DateTime}
  203.      */
  204.     public static Date getEndOf(DateTime date) {
  205.         if (Is.nil(date)) {
  206.             return getEndOf(new Date());
  207.         }
  208.         return date.
  209.                 withHourOfDay(23).
  210.                 withMinuteOfHour(59).
  211.                 withSecondOfMinute(59).toDate();
  212.     }
  213.  
  214.     /**
  215.      * Get temporal date instance of the current {@code datetime}.
  216.      * <p>
  217.      * This will truncate hour, minute, seconds and milliseconds from the given
  218.      * date.
  219.      *
  220.      * @return Temporal date
  221.      */
  222.     public static Date nowYMD() {
  223.         return tempoYMD(new Date());
  224.     }
  225.  
  226.     /**
  227.      * Get temporal date instance.
  228.      * <p>
  229.      * This will truncate hour, minute, seconds and milliseconds from the given
  230.      * date.
  231.      *
  232.      * @param date A date
  233.      * @return Temporal date
  234.      */
  235.     public static Date tempoYMD(Date date) {
  236.         return new DateTime(date).
  237.                 withHourOfDay(0).
  238.                 withMinuteOfHour(0).
  239.                 withSecondOfMinute(0).
  240.                 withMillisOfSecond(0).toDate();
  241.     }
  242.  
  243.     /**
  244.      * Get temporal date instance of the current {@code datetime}.
  245.      * <p>
  246.      * This will truncate minute, seconds and milliseconds from the given date.
  247.      *
  248.      * @return Temporal date
  249.      */
  250.     public static Date nowYMDH() {
  251.         return tempoYMDH(new Date());
  252.     }
  253.  
  254.     /**
  255.      * Get temporal date instance.
  256.      * <p>
  257.      * This will truncate minute, seconds and milliseconds from the given date.
  258.      *
  259.      * @param date A date
  260.      * @return Temporal date
  261.      */
  262.     public static Date tempoYMDH(Date date) {
  263.         return new DateTime(date).
  264.                 withMinuteOfHour(0).
  265.                 withSecondOfMinute(0).
  266.                 withMillisOfSecond(0).toDate();
  267.     }
  268.  
  269.     /**
  270.      * Get temporal date instance of the current {@code datetime}.
  271.      * <p>
  272.      * This will truncate seconds and milliseconds from the given date.
  273.      *
  274.      * @return Temporal date
  275.      */
  276.     public static Date tempoYMDHM() {
  277.         return tempoYMDHM(new Date());
  278.     }
  279.  
  280.     /**
  281.      * Get temporal date instance.
  282.      * <p>
  283.      * This will truncate seconds and milliseconds from the given date.
  284.      *
  285.      * @param date A date
  286.      * @return Temporal date
  287.      */
  288.     public static Date tempoYMDHM(Date date) {
  289.         return new DateTime(date).withSecondOfMinute(0).withMillisOfSecond(0).toDate();
  290.     }
  291.  
  292.     /**
  293.      * Convert duration to hours.
  294.      *
  295.      * @param duration Duration of time
  296.      * @return Hours of time
  297.      */
  298.     public static BigDecimal toHrBigDecimal(final BigDecimal duration) {
  299.         BigDecimal result = BigDecimal.ZERO.setScale(1);
  300.         try {
  301.             result = duration.divide(
  302.                     new BigDecimal("3600000"),
  303.                     BigDecimal.ROUND_HALF_UP)
  304.                     .setScale(1, RoundingMode.HALF_UP);
  305.         } catch (Exception e) {
  306.             LOGGER.error("Cause: {}", e.toString());
  307.         }
  308.         return result;
  309.     }
  310.  
  311.     /**
  312.      * Convert duration to minutes.
  313.      *
  314.      * @param duration Duration of time
  315.      * @return Minutes of time
  316.      */
  317.     public static int toMinuteInt(BigDecimal duration) {
  318.         int result = 0;
  319.         try {
  320.             result = duration.divide(
  321.                     new BigDecimal("60000"),
  322.                     BigDecimal.ROUND_DOWN)
  323.                     .remainder(new BigDecimal("60")).intValue();
  324.         } catch (Exception e) {
  325.             LOGGER.error("Cause: {}", e.toString());
  326.         }
  327.         return result;
  328.     }
  329.  
  330.     /**
  331.      * Converts time into different {@link TimeUnit}.
  332.      * <p>
  333.      * Useful tool for converting a time into different units.
  334.      * <br /> <br />
  335.      * Example: <br />
  336.      * <blockquote> {@code convert(60, TimeUnit.MINUTE, TimeUnit.SECONDS)} will
  337.      * return {@code 1} because 60 seconds was converted to minute.
  338.      * </blockquote>
  339.      *
  340.      * @param aTime Time of any unit
  341.      * @param convertTo Time unit conversion result
  342.      * @param convertFrom Time unit of the given {@code aTime}
  343.      * @return Converted time which time unit is based on the given
  344.      * {@code convertTo} value of {@link TimeUnit}
  345.      */
  346.     public static long convert(final long aTime, TimeUnit convertTo, TimeUnit convertFrom) {
  347.         return convertTo.convert(aTime, convertFrom);
  348.     }
  349.  
  350.     /**
  351.      * Simple unit conversion.
  352.      * <p>
  353.      * <blockquote>
  354.      * Note: <i>fraction is currently not supported for now.</i>
  355.      * </blockquote>
  356.      *
  357.      * @param seconds Seconds in time
  358.      * @return Converted millis from seconds (seconds->millis)
  359.      */
  360.     public static long secondsToNano(final long seconds) {
  361.         return TimeUnit.NANOSECONDS.convert(seconds, TimeUnit.SECONDS);
  362.     }
  363.  
  364.     /**
  365.      * Simple unit conversion.
  366.      * <p>
  367.      * <blockquote>
  368.      * Note: <i>fraction is currently not supported for now.</i>
  369.      * </blockquote>
  370.      *
  371.      * @param seconds Seconds in time
  372.      * @return Converted nanoseconds from seconds (seconds->nanos)
  373.      */
  374.     public static long secondsToMillis(final long seconds) {
  375.         return TimeUnit.MILLISECONDS.convert(seconds, TimeUnit.SECONDS);
  376.     }
  377.  
  378.     /**
  379.      * Simple unit conversion.
  380.      * <p>
  381.      * <blockquote>
  382.      * Note: <i>fraction is currently not supported for now.</i>
  383.      * </blockquote>
  384.      *
  385.      * @param minute Minutes in time
  386.      * @return Converted millis from minute (minute->millis)
  387.      */
  388.     public static long minuteToMillis(final long minute) {
  389.         return TimeUnit.MILLISECONDS.convert(minute, TimeUnit.MINUTES);
  390.     }
  391.  
  392.     /**
  393.      * Simple unit conversion.
  394.      * <p>
  395.      * <blockquote>
  396.      * Note: <i>fraction is currently not supported for now.</i>
  397.      * </blockquote>
  398.      *
  399.      * @param minute Minutes in time
  400.      * @return Converted seconds from minutes (minutes->seconds)
  401.      */
  402.     public static long minuteToSeconds(final long minute) {
  403.         return TimeUnit.SECONDS.convert(minute, TimeUnit.MINUTES);
  404.     }
  405.  
  406.     /**
  407.      * Simple unit conversion.
  408.      * <p>
  409.      * <blockquote>
  410.      * Note: <i>fraction is currently not supported for now.</i>
  411.      * </blockquote>
  412.      *
  413.      * @param hour Hour in time
  414.      * @return Converted millis from hour (hours->millis)
  415.      */
  416.     public static long hourToMillis(final long hour) {
  417.         return TimeUnit.MILLISECONDS.convert(hour, TimeUnit.HOURS);
  418.     }
  419.  
  420.     /**
  421.      * Simple unit conversion.
  422.      * <p>
  423.      * <blockquote>
  424.      * Note: <i>fraction is currently not supported for now.</i>
  425.      * </blockquote>
  426.      *
  427.      * @param hour Hour in time
  428.      * @return Converted seconds from hour (hours->seconds)
  429.      */
  430.     public static long hourToSeconds(final long hour) {
  431.         return TimeUnit.SECONDS.convert(hour, TimeUnit.HOURS);
  432.     }
  433.  
  434.     /**
  435.      * Simple unit conversion.
  436.      * <p>
  437.      * <blockquote>
  438.      * Note: <i>fraction is currently not supported for now.</i>
  439.      * </blockquote>
  440.      *
  441.      * @param hour Hour in time
  442.      * @return Converted minute from hour (hours->minute)
  443.      */
  444.     public static long hourToMinute(final long hour) {
  445.         return TimeUnit.MINUTES.convert(hour, TimeUnit.HOURS);
  446.     }
  447.  
  448.     /**
  449.      * Convert milliseconds to date format.
  450.      * <p>
  451.      * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day, 10 hrs
  452.      * 17 mins, 36 sec </b> </i>
  453.      *
  454.      * @param millis Milliseconds of time
  455.      * @return Formatted date and time
  456.      * @see Times#toDateWord(long) toDateWord() is a good alternative
  457.      */
  458.     public static String toDate(final long millis) {
  459.         long _millis = millis;
  460.         final long SECOND = 1000;
  461.         final long MINUTE = 60 * SECOND;
  462.         final long HOUR = 60 * MINUTE;
  463.         final long DAY = 24 * HOUR;
  464.         final StringBuffer text = new StringBuffer();
  465.         if (_millis > DAY) {
  466.             final long _day = _millis / DAY;
  467.             text.append(_day).append(_day > 1 ? " days" : " day");
  468.             _millis = _millis % DAY;
  469.         }
  470.         if (_millis > HOUR) {
  471.             text.append(", ");
  472.             final long _hour = _millis / HOUR;
  473.             text.append(_hour).append(_hour > 1 ? " hrs" : " hr");
  474.             _millis = _millis % HOUR;
  475.         }
  476.         if (_millis > MINUTE) {
  477.             text.append(", ");
  478.             final long _minute = _millis / MINUTE;
  479.             text.append(_minute).append(_minute > 1 ? " mins" : " min");
  480.             _millis = _millis % MINUTE;
  481.         }
  482.         if (_millis > SECOND) {
  483.             text.append(", ");
  484.             text.append(_millis / SECOND).append("sec");
  485.         }
  486.         return text.toString();
  487.     }
  488.  
  489.     /**
  490.      * Convert milliseconds to date worded format.
  491.      * <p>
  492.      * Example:
  493.      * <pre><i> millis = <b> 123456789 </b> will result to <b> 1 day, 10 hrs
  494.      * 17 mins, 36 sec </b> </i></pre>
  495.      * <br/ >
  496.      * <i> Note: Any caught exception will return {@code null}. Also a negative
  497.      * millis value will immediately return {@code null}.</i>
  498.      *
  499.      * @param date {@link Date}
  500.      * @return Formatted date and time
  501.      */
  502.     public static String toDateWord(final Date date) {
  503.         return toDateWord(date.getTime());
  504.     }
  505.  
  506.     /**
  507.      * Convert milliseconds to date worded format.
  508.      * <p>
  509.      * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day, 10 hrs
  510.      * 17 mins, 36 sec </b> </i>
  511.      * <br/ >
  512.      * <i> Note: Any caught exception will return {@code null}. Also a negative
  513.      * millis value will immediately return {@code null}.</i>
  514.      *
  515.      * @param millis A time in millis
  516.      * @return Formatted date and time.
  517.      */
  518.     public static String toDateWord(final long millis) {
  519.         if (millis < 0) {
  520.             LOGGER.error("Invalid millis! It must be a valid non-negative numerical value!");
  521.             return null;
  522.         }
  523.         return new PeriodFormatterBuilder()
  524.                 .appendYears() // Year
  525.                 .appendSuffix(" year", " years")
  526.                 .appendSeparator(", ")
  527.                 .appendDays() // Day
  528.                 .appendSuffix(" day", " days")
  529.                 .appendSeparator(", ")
  530.                 .appendHours() // Hour
  531.                 .appendSuffix(" hr", " hrs")
  532.                 .appendSeparator(", ")
  533.                 .appendMinutes() // Min
  534.                 .appendSuffix(" min", " min")
  535.                 .appendSeparator(", ")
  536.                 .appendSeconds() // Sec
  537.                 .appendSuffix(" sec")
  538.                 .toFormatter().print(new Period(millis).normalizedStandard(
  539.                                 PeriodType.standard()
  540.                                 .withMonthsRemoved()
  541.                                 .withWeeksRemoved()
  542.                                 .withMillisRemoved()));
  543.     }
  544.  
  545.     /**
  546.      * Convert milliseconds to date colon format.
  547.      * <p>
  548.      * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day,
  549.      * 10:17:36 </b> </i>
  550.      * <br/ >
  551.      * <i> Note: Any caught exception will return {@code null}. Also a negative
  552.      * millis value will immediately return {@code null}.</i>
  553.      *
  554.      * @param date {@link Date}
  555.      * @return Formatted date and time
  556.      */
  557.     public static String toDateColon(final Date date) {
  558.         return toDateColon(date.getTime());
  559.     }
  560.  
  561.     /**
  562.      * Convert milliseconds to date colon format.
  563.      * <p>
  564.      * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day,
  565.      * 10:17:36 </b> </i>
  566.      * <br/ >
  567.      * <i> Note: Any caught exception will return {@code null}. Also a negative
  568.      * millis value will immediately return {@code null}.</i>
  569.      *
  570.      * @param millis A time in millis
  571.      * @return Formatted date and time
  572.      */
  573.     public static String toDateColon(final long millis) {
  574.         if (millis < 0) {
  575.             LOGGER.error("Invalid millis! It must be a valid non-negative numerical value!");
  576.             return null;
  577.         }
  578.         return new PeriodFormatterBuilder()
  579.                 .printZeroAlways() // Hour
  580.                 .minimumPrintedDigits(2)
  581.                 .maximumParsedDigits(3)
  582.                 .appendHours()
  583.                 .appendSeparator(":")
  584.                 .printZeroAlways() // Minute
  585.                 .minimumPrintedDigits(2)
  586.                 .appendMinutes()
  587.                 .appendSeparator(":")
  588.                 .printZeroAlways() // Sec
  589.                 .minimumPrintedDigits(2)
  590.                 .appendSeconds()
  591.                 .toFormatter().print(new Period(millis).normalizedStandard(
  592.                                 PeriodType.standard()
  593.                                 .withYearsRemoved()
  594.                                 .withMonthsRemoved()
  595.                                 .withWeeksRemoved()
  596.                                 .withDaysRemoved()
  597.                                 .withMillisRemoved()));
  598.     }
  599.  
  600.     /**
  601.      * Format the current date (today) to String format.
  602.      * <p>
  603.      * Customize the format of the current Date instance based on your specified
  604.      * date format. This will
  605.      *
  606.      * <blockquote>
  607.      * <b>Example:</b>
  608.      * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
  609.      * "10/23/1992 09:09:09 AM"
  610.      * </blockquote>
  611.      * <br /><br />
  612.      * <i> Note: Any caught exception will return {@code null}. Also a
  613.      * {@code null} {@code pattern} will immediately return {@code null}.</i>
  614.      *
  615.      * @param pattern Your own date format
  616.      * @return Formatted date based on the specified date
  617.      */
  618.     public static synchronized String toDateFormat(final String pattern) {
  619.         if (Is.empty(pattern)) {
  620.             LOGGER.info("Date pattern is null or empty! Returning null...");
  621.             return null;
  622.         }
  623.         return toDateFormat(new Date(), pattern);
  624.     }
  625.  
  626.     /**
  627.      * Format date to String format.
  628.      * <p>
  629.      * Customize the format of your Date instance based on your specified date
  630.      * format. This will
  631.      *
  632.      * <blockquote>
  633.      * <b>Example:</b>
  634.      * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
  635.      * "10/23/1992 09:09:09 AM"
  636.      * </blockquote>
  637.      * <br /><br />
  638.      * <i> Note: Any caught exception will return {@code null}. Also a
  639.      * {@code null} {@code date} value will immediately return {@code null}.</i>
  640.      *
  641.      * @param date Date you want to changed format
  642.      * @param pattern Your own date format
  643.      * @return Formatted date based on the specified date
  644.      */
  645.     public static String toDateFormat(final DateTime date, final String pattern) {
  646.         String result = null;
  647.         if (date == null) {
  648.             LOGGER.info("Null value! Returning null...");
  649.             return result;
  650.         }
  651.         try {
  652.             result = date.toString(pattern, Locale.getDefault());
  653.         } catch (IllegalArgumentException e) {
  654.             LOGGER.error("Cause: {}", e.toString());
  655.         }
  656.         return result;
  657.     }
  658.  
  659.     /**
  660.      * Format date to String format.
  661.      * <p>
  662.      * Customize the format of your Date instance based on your specified date
  663.      * format. This will
  664.      *
  665.      * <blockquote>
  666.      * <b>Example:</b>
  667.      * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
  668.      * "10/23/1992 09:09:09 AM"
  669.      * </blockquote>
  670.      * <br /><br />
  671.      * <i> Note: Any caught exception will return {@code null}. Also a
  672.      * {@code null} {@code date} value will immediately return {@code null}.</i>
  673.      *
  674.      * @param date Date you want to changed format
  675.      * @param pattern Your own date format
  676.      * @return Formatted date based on the specified date, {@code null} if an
  677.      * exception was caught
  678.      */
  679.     public static synchronized String toDateFormat(final Date date, final String pattern) {
  680.         String result = null;
  681.         if (date == null) {
  682.             LOGGER.info("Null value! Returning null...");
  683.             return result; // Return immediately
  684.         }
  685.         try {
  686.             result = new DateTime(date).toString(pattern, Locale.getDefault());
  687.         } catch (IllegalArgumentException e) {
  688.             LOGGER.error("Cause: {}", e.toString());
  689.         }
  690.         return result;
  691.     }
  692.  
  693.     /**
  694.      * Parses text from the beginning of the given string to produce a date.
  695.      * <p>
  696.      * The method may not use the entire text of the given string.
  697.      *
  698.      * <blockquote>
  699.      * <b>Example:</b>
  700.      * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
  701.      * "10/23/1992 09:09:09 AM"
  702.      * </blockquote>
  703.      * <br /><br />
  704.      * <i> Note: Any caught exception will return null. </i>
  705.      *
  706.      * @param date Date you want to changed format
  707.      * @param pattern Your own date format
  708.      * @param dflt Default value
  709.      * @return Parsed Date instance, {@code dflt} if ParseExceptin was caught
  710.      */
  711.     public static Date toDateFormat(Date date, String pattern, Date dflt) {
  712.         try {
  713.             return new SimpleDateFormat(pattern).parse(toDateFormat(date, pattern));
  714.         } catch (ParseException e) {
  715.             LOGGER.debug("Formatting Date failed - Cause: {} - Returning dflt value ({})", e.toString(), dflt);
  716.             return dflt;
  717.         }
  718.     }
  719.  
  720.     /**
  721.      * Convert duration to hours.
  722.      *
  723.      * @param duration Duration of time
  724.      * @return Hours of time
  725.      */
  726.     public static long durationToHourInt(BigDecimal duration) {
  727.         return duration.divide(new BigDecimal("3600000"), BigDecimal.ROUND_DOWN).longValue();
  728.     }
  729.  
  730.     /**
  731.      * Set the time of the given date to the given time-format string. For
  732.      * Example, the date you've given is (1992-10-23) and the time you've given
  733.      * is (11:40am), the date you'll get is 1992-10-23 11:40.
  734.      *
  735.      * @param date Any valid date
  736.      * @param time Any valid time format
  737.      * @return Date with the given time. Will return the same date if an
  738.      * exception was caught.
  739.      */
  740.     public static Date getDateWithTime(Date date, String time) {
  741.         Date result = date;
  742.         try {
  743.             final DateTime datetime = new DateTime(date);
  744.             int hour = Integer.parseInt(time.substring(0, 1));
  745.             int minute = Integer.parseInt(time.substring(3, 4));
  746.             if (time.substring(5).equalsIgnoreCase("pm")) {
  747.                 hour += 12;
  748.             }
  749.             result = datetime.withTime(hour, minute, 0, 0).toDate();
  750.         } catch (NumberFormatException e) {
  751.             LOGGER.error("Cause: {}", e.toString());
  752.         }
  753.         return result;
  754.     }
  755.  
  756.     /**
  757.      * Gets the day of week name.
  758.      *
  759.      * @param date the basis date.
  760.      * @return the name of the day of week of the date parameter.
  761.      */
  762.     public static String getDayOfWeekName(Date date) {
  763.         final int dayOfWeek = getDayOfWeek(date);
  764.         return (dayOfWeek == 1) ? "Monday"
  765.                 : (dayOfWeek == 2) ? "Tuesday"
  766.                         : (dayOfWeek == 3) ? "Wednesday"
  767.                                 : (dayOfWeek == 4) ? "Thursday"
  768.                                         : (dayOfWeek == 5) ? "Friday"
  769.                                                 : (dayOfWeek == 6) ? "Saturday"
  770.                                                         : (dayOfWeek == 7) ? "Sunday" : "";
  771.     }
  772.  
  773.     /**
  774.      * Gets the day of week in integer.
  775.      *
  776.      * @param date Date basis to get the day of week.
  777.      * @return The {@code nth} position of the date day of week
  778.      */
  779.     public static int getDayOfWeek(Date date) {
  780.         return new DateTime(date).getDayOfWeek();
  781.     }
  782.  
  783.     /**
  784.      * Compares DateTime's month, day and year.
  785.      * <p>
  786.      * Seconds and milliseconds are ignored in this comparator.
  787.      *
  788.      * @param dt1 A DateTime
  789.      * @param dt2 Another DateTime
  790.      * @return True if both DateTime has equal month, day and year, otherwise
  791.      * false
  792.      */
  793.     public static boolean compareDateTime(DateTime dt1, DateTime dt2) {
  794.         return (dt1.getMonthOfYear() == dt2.getMonthOfYear())
  795.                 && (dt1.getDayOfMonth() == dt2.getDayOfMonth())
  796.                 && (dt1.getYear() == dt2.getYear());
  797.     }
  798.  
  799.     /**
  800.      * This puts zero in from of the time-format string.
  801.      * <p>
  802.      * It will return the same string if there's already a zero in front.
  803.      *
  804.      * @param time A time
  805.      * @return The time-format {@link String}
  806.      */
  807.     public static String putZero(String time) {
  808.         return time.startsWith("0") ? "0" + time : time;
  809.     }
  810.  
  811.     /**
  812.      * Get day today in instance of String.
  813.      * <p>
  814.      *
  815.      * <blockquote>
  816.      * <b>Example:</b>
  817.      * "Monday", "Friday"
  818.      * </blockquote>
  819.      *
  820.      * @return Day today.
  821.      */
  822.     public static String getDay() {
  823.         return toDateFormat(new Date(), "EEEE");
  824.     }
  825.  
  826.     /**
  827.      * Get date today in instance of String according to your own format.
  828.      * <p>
  829.      * <blockquote>
  830.      * <b>Example:</b>
  831.      * pattern = (mm/dd/yyyy) will result to "10231992"
  832.      * </blockquote>
  833.      * <i>
  834.      * Note: Any caught exception such as NumberFormatException will return 0,
  835.      * so you may know from your top-level class that there was caught
  836.      * exception.
  837.      * </i>
  838.      *
  839.      * @param pattern Your own date format
  840.      * @return Date today according to your format, then 0 if there's a caught
  841.      * exception.
  842.      */
  843.     public static int getDate(String pattern) {
  844.         return Numbers.get(toDateFormat(new Date(), pattern).replaceAll("\\D", ""));
  845.     }
  846.  
  847.     /**
  848.      * Get the current month.
  849.      * <p>
  850.      * Used the pattern <code>"MM"</code> pattern to get the month.
  851.      *
  852.      * @return The current month, zero (0) if an error occur
  853.      */
  854.     public static int getMonth() {
  855.         return Numbers.get(toDateFormat("MM"));
  856.     }
  857.  
  858.     /**
  859.      * Get the current year.
  860.      * <p>
  861.      * Used the pattern <code>"YY"</code> pattern to get the year.
  862.      *
  863.      * @return The current year, zero (0) if an error occur
  864.      */
  865.     public static int getYearYY() {
  866.         return Numbers.get(toDateFormat("YY"));
  867.     }
  868.  
  869.     /**
  870.      * Get the current year.
  871.      * <p>
  872.      * Used the pattern <code>"yyyy"</code> pattern to get the year.
  873.      *
  874.      * @return The current year, zero (0) if an error occur
  875.      */
  876.     public static int getYearYYYY() {
  877.         return Numbers.get(toDateFormat("yyyy"));
  878.     }
  879.  
  880.     /**
  881.      * Get the hour time from the given {@code dateTime}.
  882.      * <p>
  883.      * Datetime format will based on the given {@code pattern}. Format or
  884.      * pattern should have "hh" or "HH" to get the hour time.
  885.      *
  886.      * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
  887.      * 21:30)
  888.      * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
  889.      * @param hour24Format 24-hour base {@code dateTime} (eg. 23:59)?
  890.      * @return If hour24Format is true, returns hour in 24-hour based time
  891.      * format, otherwise 12-hour based format
  892.      * @see Times#getHrFromDateStr(java.lang.String, java.lang.String, boolean)
  893.      *
  894.      */
  895.     public static int getHrFromDate(String dateTime, String pattern, boolean hour24Format) {
  896.         return Numbers.get(
  897.                 getHrFromDateStr(dateTime, pattern, hour24Format),
  898.                 0);
  899.     }
  900.  
  901.     /**
  902.      * Get the hour time from the given {@code dateTime}.
  903.      * <p>
  904.      * Datetime format will based on the given {@code pattern}. Format or
  905.      * pattern should have "hh" or "HH" to get the hour time.
  906.      *
  907.      * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
  908.      * 21:30)
  909.      * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
  910.      * @param hour24Format 24-hour base {@code dateTime} (eg. 23:59)?
  911.      * @return If hour24Format is true, returns hour in 24-hour based time
  912.      * format, otherwise 12-hour based format
  913.      * @see Times#getHrFromDate(java.lang.String, java.lang.String, boolean)
  914.      */
  915.     public static String getHrFromDateStr(String dateTime, String pattern, boolean hour24Format) {
  916.         return DateTimeFormat.forPattern(pattern).
  917.                 parseDateTime(dateTime).
  918.                 toString(hour24Format ? "HH" : "hh");
  919.     }
  920.  
  921.     /**
  922.      * Get the minute time from the given {@code dateTime}.
  923.      * <p>
  924.      * Datetime format will based on the given {@code pattern}. Format or
  925.      * pattern should have "mm" to get the minute time. Don't get confuse to
  926.      * format "MM" and "mm" as the uppercase format is for month not minute.
  927.      *
  928.      * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
  929.      * 21:30)
  930.      * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
  931.      * @return Minute value
  932.      * @see Times#getHrFromDate(java.lang.String, java.lang.String, boolean)
  933.      */
  934.     public static int getMinFromDate(String dateTime, String pattern) {
  935.         return Numbers.get(getMinFromDateStr(dateTime, pattern), 0);
  936.     }
  937.  
  938.     /**
  939.      * Get the minute time from the given {@code dateTime}.
  940.      * <p>
  941.      * Datetime format will based on the given {@code pattern}. Format or
  942.      * pattern should have "mm" to get the minute time. Don't get confuse to
  943.      * format "MM" and "mm" as the uppercase format is for month not minute.
  944.      *
  945.      *
  946.      * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
  947.      * 21:30)
  948.      * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
  949.      * @return Minute value
  950.      * @see Times#getHrFromDate(java.lang.String, java.lang.String, boolean)
  951.      * value
  952.      */
  953.     public static String getMinFromDateStr(String dateTime, String pattern) {
  954.         return DateTimeFormat.forPattern(pattern).parseDateTime(dateTime).
  955.                 toString("mm");
  956.     }
  957.  
  958.     /**
  959.      * Converts the given {@code dateTime} with type of {@code String} to
  960.      * instance of {@link DateTime}.
  961.      * <p>
  962.      * The given {@code dateTime} should be appropriate to the given
  963.      * {@code pattern}.
  964.      * <br />
  965.      * Note: <i> Format will not be retain if {@link DateTime#toString()} was
  966.      * invoke, use {@link DateTime#toString(java.lang.String)} instead to have
  967.      * your own date format. </i>
  968.      *
  969.      * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
  970.      * 21:30)
  971.      * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
  972.      * @return Instance of {@link DateTime} from the given {@code dateTime}
  973.      */
  974.     public static DateTime toDateTime(String dateTime, String pattern) {
  975.         try {
  976.             return DateTimeFormat.forPattern(pattern).parseDateTime(dateTime);
  977.         } catch (Exception e) {
  978.             LOGGER.error("Cause: {}", e.toString());
  979.             return null;
  980.         }
  981.     }
  982.  
  983.     /**
  984.      * Converts the given {@code dateTime} with type of {@code String} to
  985.      * instance of {@link Date}.
  986.      * <p>
  987.      * The given {@code dateTime} should be appropriate to the given
  988.      * {@code pattern}.
  989.      * <br />
  990.      * Note: <i> Format will not be retain if {@link Date#toString()} was
  991.      * invoke, use {@link DateTime#toString(java.lang.String)} instead to have
  992.      * your own date format. </i>
  993.      *
  994.      * @param dateTime A {@code Date} in type of {@code String}
  995.      * @param pattern Date format or pattern
  996.      * @return Instance of {@link Date} from the given {@code dateTime}
  997.      */
  998.     public static Date toDate(String dateTime, String pattern) {
  999.         final DateTime result = toDateTime(dateTime, pattern);
  1000.         return Is.nil(result) ? null : result.toDate();
  1001.     }
  1002.  
  1003.     /**
  1004.      * Set the time of date given.
  1005.      * <p>
  1006.      * The given {@code time} should be in format of "HH:mm" or "hh:mm".
  1007.      *
  1008.      * @param date Date to be modified
  1009.      * @param time Time to be evaluated
  1010.      * @param hour24Format 24-hour base {@code dateTime} (eg. 23:59)?
  1011.      * @return Instance of {@code java.util.Date} with the given time
  1012.      */
  1013.     public static Date setTimeFromDate(Date date, String time, boolean hour24Format) {
  1014.         final String format = (hour24Format) ? "HH:mm" : "hh:mm";
  1015.         return new DateTime(date).
  1016.                 withHourOfDay(Times.getHrFromDate(time, format, hour24Format)).
  1017.                 withMinuteOfHour(Times.getMinFromDate(time, format)).
  1018.                 toDate();
  1019.     }
  1020.  
  1021.     /**
  1022.      * Gets the hour in the given date.
  1023.      *
  1024.      * @param date Date where the hour will be come from
  1025.      * @return Hour of the given date
  1026.      */
  1027.     public static int getHrFromDate(Date date) {
  1028.         return new DateTime(date).getHourOfDay();
  1029.     }
  1030.  
  1031.     /**
  1032.      * Adds days in the given date.
  1033.      *
  1034.      * @param date Date to be modified
  1035.      * @param years Number of years to be added
  1036.      * @return Instance of {@code java.util.Date} with years added.
  1037.      */
  1038.     public static Date plusYear(Date date, int years) {
  1039.         return new DateTime(date).plusYears(years).toDate();
  1040.     }
  1041.  
  1042.     /**
  1043.      * Subtracts days in the given date.
  1044.      *
  1045.      * @param date Date to be modified
  1046.      * @param years Number of year to be subtracted
  1047.      * @return Instance of {@code java.util.Date} with years subtracted
  1048.      */
  1049.     public static Date minusYear(Date date, int years) {
  1050.         return new DateTime(date).minusYears(years).toDate();
  1051.     }
  1052.  
  1053.     /**
  1054.      * Adds days in the given date.
  1055.      *
  1056.      * @param date Date to be modified
  1057.      * @param weeks Number of weeks to be added
  1058.      * @return Instance of {@code java.util.Date} with weeks added.
  1059.      */
  1060.     public static Date plusWeek(Date date, int weeks) {
  1061.         return new DateTime(date).plusWeeks(weeks).toDate();
  1062.     }
  1063.  
  1064.     /**
  1065.      * Subtracts days in the given date.
  1066.      *
  1067.      * @param date Date to be modified
  1068.      * @param weeks Number of weeks to be subtracted
  1069.      * @return Instance of {@code java.util.Date} with weeks subtracted
  1070.      */
  1071.     public static Date minusWeek(Date date, int weeks) {
  1072.         return new DateTime(date).minusWeeks(weeks).toDate();
  1073.     }
  1074.  
  1075.     /**
  1076.      * Adds days in the given date.
  1077.      *
  1078.      * @param date Date to be modified
  1079.      * @param days Number of days to be added
  1080.      * @return Instance of {@code java.util.Date} with days added.
  1081.      */
  1082.     public static Date plusDay(Date date, int days) {
  1083.         return new DateTime(date).plusDays(days).toDate();
  1084.     }
  1085.  
  1086.     /**
  1087.      * Subtracts days in the given date.
  1088.      *
  1089.      * @param date Date to be modified
  1090.      * @param days Number of days to be subtracted
  1091.      * @return Instance of {@code java.util.Date} with days subtracted
  1092.      */
  1093.     public static Date minusDay(Date date, int days) {
  1094.         return new DateTime(date).minusDays(days).toDate();
  1095.     }
  1096.  
  1097.     /**
  1098.      * Adds hours in the given date.
  1099.      *
  1100.      * @param date Date to be modified
  1101.      * @param hours Number of hours to be added
  1102.      * @return Instance of {@code java.util.Date} with hours added
  1103.      */
  1104.     public static Date plusHour(Date date, int hours) {
  1105.         return new DateTime(date).plusHours(hours).toDate();
  1106.     }
  1107.  
  1108.     /**
  1109.      * Subtracts hours in the given date.
  1110.      *
  1111.      * @param date Date to be modified
  1112.      * @param hours Number of hours to be subtracted
  1113.      * @return Instance of {@code java.util.Date} with hours subtracted
  1114.      */
  1115.     public static Date minusHour(Date date, int hours) {
  1116.         return new DateTime(date).minusHours(hours).toDate();
  1117.     }
  1118.  
  1119.     /**
  1120.      * Adds minutes in the time of the date.
  1121.      *
  1122.      * @param date Date to be modified
  1123.      * @param minutes Number of minutes to be added
  1124.      * @return Instance of {@code java.util.Date} with minutes added
  1125.      */
  1126.     public static Date plusMinute(Date date, int minutes) {
  1127.         return new DateTime(date).plusMinutes(minutes).toDate();
  1128.     }
  1129.  
  1130.     /**
  1131.      * Subtracts minutes in the time of the date.
  1132.      *
  1133.      * @param date Date to be modified
  1134.      * @param minutes Number of minutes to be subtracted
  1135.      * @return Instance of {@code java.util.Date} with minutes subtracted
  1136.      */
  1137.     public static Date minusMinute(Date date, int minutes) {
  1138.         return new DateTime(date).minusMinutes(minutes).toDate();
  1139.     }
  1140.  
  1141.     /**
  1142.      * Adds minutes in the time of the date.
  1143.      *
  1144.      * @param date Date to be modified
  1145.      * @param minutes Number of minutes to be added
  1146.      * @return Instance of {@code java.util.Date} with minutes added
  1147.      */
  1148.     public static Date plusSecond(Date date, int minutes) {
  1149.         return new DateTime(date).plusSeconds(minutes).toDate();
  1150.     }
  1151.  
  1152.     /**
  1153.      * Subtracts minutes in the time of the date.
  1154.      *
  1155.      * @param date Date to be modified
  1156.      * @param minutes Number of minutes to be subtracted
  1157.      * @return Instance of {@code java.util.Date} with minutes subtracted
  1158.      */
  1159.     public static Date minusSecond(Date date, int minutes) {
  1160.         return new DateTime(date).minusSeconds(minutes).toDate();
  1161.     }
  1162.  
  1163.     /**
  1164.      * Gets the seconds difference of the two dates.
  1165.      * <p>
  1166.      * The second date must always be the larger to obtain a positive value.
  1167.      *
  1168.      * @param firstDate First date or in subtraction, the subtrahend
  1169.      * @param secondDate Second date or in subtraction, the minuend
  1170.      * @return Seconds difference of the two dates
  1171.      */
  1172.     public static int getSecDiff(Date firstDate, Date secondDate) {
  1173.         return Numbers.toInt(new Duration(firstDate.getTime(), secondDate.getTime()).getStandardSeconds());
  1174.     }
  1175.  
  1176.     /**
  1177.      * Time format for
  1178.      * {@link Times#convertTime(java.lang.String, my.jutils.Times.TimeFormat)}.
  1179.      */
  1180.     public static enum TimeFormat {
  1181.  
  1182.         /**
  1183.          * 12-hour format.
  1184.          */
  1185.         Twelve,
  1186.         /**
  1187.          * 24-hour format.
  1188.          */
  1189.         TwentyFour;
  1190.     }
  1191.  
  1192.     /**
  1193.      * Converts time based on the given format.
  1194.      *
  1195.      * @param time Time to be converted {@code (Eg. 9:00am or 19:00)}
  1196.      * @param format Output format of the time from {@link TimeFormat}
  1197.      * @return Formatted time, otherwise {@code empty String} if the
  1198.      * {@code time} given was null or empty
  1199.      */
  1200.     public static String convertTime(String time, TimeFormat format) {
  1201.         if (Is.empty(time)) {
  1202.             return "";
  1203.         }
  1204.         String currentFormat;
  1205.         String newFormat;
  1206.         String result = "";
  1207.         if (TimeFormat.Twelve == format) {
  1208.             currentFormat = "HH:mm";
  1209.             newFormat = "hh:mma";
  1210.         } else { // If time convert to 24-hour format
  1211.             newFormat = "HH:mm";
  1212.             currentFormat = "hh:mma";
  1213.         }
  1214.         try {
  1215.             result = new SimpleDateFormat(newFormat).
  1216.                     format(new SimpleDateFormat(currentFormat).parse(time));
  1217.         } catch (ParseException e) {
  1218.             LOGGER.error("Cause: {}", e.toString());
  1219.         }
  1220.         return result;
  1221.     }
  1222.  
  1223.     /**
  1224.      * Converts the native java date ({@link Date}) to SQL date instance.
  1225.      *
  1226.      * @param date instance of {@link Date}
  1227.      * @return instance of SQL date otherwise if date is null, will return null
  1228.      */
  1229.     public static java.sql.Date toSQLDate(java.util.Date date) {
  1230.         return new java.sql.Date(date.getTime());
  1231.     }
  1232.  
  1233.     /**
  1234.      * Converts the native java date ({@link Date}) to SQL timestamp instance.
  1235.      *
  1236.      * @param date instance of {@link Date}
  1237.      * @return instance of SQL timestamp otherwise if date is null, will return
  1238.      * null
  1239.      */
  1240.     public static java.sql.Timestamp toSQLTimeStamp(java.util.Date date) {
  1241.         return new java.sql.Timestamp(date.getTime());
  1242.     }
  1243.  
  1244. }
Advertisement
Add Comment
Please, Sign In to add comment