Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package my.jutils;
- import java.math.*;
- import java.text.*;
- import java.util.*;
- import java.util.concurrent.TimeUnit;
- import org.joda.time.*;
- import org.joda.time.format.*;
- import org.slf4j.*;
- /**
- * Utility for Date and Time processing.
- * <p>
- * We've use Joda-Time framework on some methods under this utility.
- *
- * @author Erieze and Einar Lagera
- */
- public class Times {
- private static final Logger LOGGER = LoggerFactory.getLogger(Times.class);
- /**
- * {@link DateTimeZone} instance for {@code Manila}.
- */
- public static final DateTimeZone MANILA_TIMEZONE = DateTimeZone.forID("Asia/Manila");
- /**
- * Gets the integer time from the current date.
- * <p>
- * Example: Date is <i>19921023 12:30:00</i>, it will get first the
- * <u>12:30</u> from the time and then replaces all the non-digit value into
- * blank to extract the number only which will be <b>1230</b>.
- *
- * @return Exact time in type of {@code int} without non-digit character
- */
- public static int getTime() {
- return Numbers.get(toDateFormat(new Date(), "HH:mm").replaceAll("\\D", ""));
- }
- /**
- * Gets the integer time from date.
- * <p>
- * Example: Date is <i>19921023 12:30:00</i>, it will get first the
- * <u>12:30</u> from the time and then replaces all the non-digit value into
- * blank to extract the number only which will be <b>1230</b>.
- *
- * @param date A {@link Date}
- * @return Exact time in type of {@code int} without non-digit character
- */
- public static int getTime(Date date) {
- if (Is.nil(date)) {
- LOGGER.info("Invalid date value!");
- return 0;
- }
- return Numbers.get(toDateFormat(date, "HH:mm").replaceAll("\\D", ""));
- }
- /**
- * Converts the {@link String} formatted {@code time} to type of
- * {@code int}.
- * <p>
- * The time should be 24-hour format or you may not get the correct hour of
- * day. Example: <code><i>12:30 -> 1230</i></code>
- *
- * @param time A 24-hour time format in type of {@link String}
- * @return Exact time in type of {@code int} without non-digit character
- */
- public static int toTime(String time) {
- return Numbers.get(time.replaceAll("\\D", ""));
- }
- /**
- * Evaluate value if {@code Date} is null.
- * <p>
- * If value is null, then the default value will be used.
- *
- * @param val Value of {@link Date}
- * @param dflt Default value
- * @return {@code dflt} if equal to {@code null}, otherwise {@code val}
- */
- public static Date get(Date val, Date dflt) {
- if (Is.nil(val)) {
- LOGGER.debug("val is null - Returning dflt value ({})", dflt);
- return dflt;
- }
- return val;
- }
- /**
- * Evaluate value if {@code Date} is null.
- * <p>
- * If value is null, then the default value will be used.
- *
- * @param val Value of {@link Date}
- * @param dflt Default value
- * @return {@code dflt} if not instance of {@link Date} or equal to
- * {@code null}, otherwise {@code val}
- */
- public static Date get(Object val, Date dflt) {
- if (Is.nil(val)) {
- LOGGER.debug("val is null - Returning dflt value ({})", dflt);
- return dflt;
- }
- if (val instanceof Date) {
- return (Date) val;
- } else {
- LOGGER.info("val is not instance of Date - Returning dflt value ({})", dflt);
- return dflt;
- }
- }
- /**
- * Safely copies {@link Date} to have protected mutable passing of
- * reference.
- *
- * @param date A {@link Date}
- * @return Cloned {@code date}
- */
- public static Date newDate(Date date) {
- return Is.nil(date) ? null : new Date(date.getTime());
- }
- /**
- * Gets the very start time of the current date.
- *
- * @return The very start time of the date today
- */
- public static Date getStartOf() {
- return new DateTime().withZone(MANILA_TIMEZONE).
- withHourOfDay(0).
- withMinuteOfHour(0).
- withSecondOfMinute(0).toDate();
- }
- /**
- * Gets the very start time of the given {@link Date}.
- * <p>
- * If null, it will use the current date.
- * </p>
- *
- * @param date A {@link Date}
- * @return The very start time of {@link Date}
- */
- public static Date getStartOf(Date date) {
- return new DateTime(get(date, new Date())).
- withHourOfDay(0).
- withMinuteOfHour(0).
- withSecondOfMinute(0).toDate();
- }
- /**
- * Gets the very start time of the given {@link DateTime}.
- * <p>
- * If null, it will use the current date.
- * </p>
- *
- * @param date A {@link DateTime}
- * @return The very start time of {@link DateTime}
- */
- public static Date getStartOf(DateTime date) {
- if (Is.nil(date)) {
- return getStartOf(new Date());
- }
- return date.
- withHourOfDay(0).
- withMinuteOfHour(0).
- withSecondOfMinute(0).toDate();
- }
- /**
- * Gets the end time of the current date.
- *
- * @return The end time of the current date.
- */
- public static Date getEndOf() {
- return new DateTime().withZone(MANILA_TIMEZONE).
- withHourOfDay(23).
- withMinuteOfHour(59).
- withSecondOfMinute(59).toDate();
- }
- /**
- * Gets the end time of the given {@link Date}.
- * <p>
- * If null, it will use the current date.
- *
- * @param date A {@link Date}
- * @return The end time of {@link Date}
- */
- public static Date getEndOf(Date date) {
- return new DateTime(get(date, new Date())).
- withHourOfDay(23).
- withMinuteOfHour(59).
- withSecondOfMinute(59).toDate();
- }
- /**
- * Gets the end time of the given {@link DateTime}.
- * <p>
- * If null, it will use the current date.
- *
- * @param date A {@link DateTime}
- * @return The end time of {@link DateTime}
- */
- public static Date getEndOf(DateTime date) {
- if (Is.nil(date)) {
- return getEndOf(new Date());
- }
- return date.
- withHourOfDay(23).
- withMinuteOfHour(59).
- withSecondOfMinute(59).toDate();
- }
- /**
- * Get temporal date instance of the current {@code datetime}.
- * <p>
- * This will truncate hour, minute, seconds and milliseconds from the given
- * date.
- *
- * @return Temporal date
- */
- public static Date nowYMD() {
- return tempoYMD(new Date());
- }
- /**
- * Get temporal date instance.
- * <p>
- * This will truncate hour, minute, seconds and milliseconds from the given
- * date.
- *
- * @param date A date
- * @return Temporal date
- */
- public static Date tempoYMD(Date date) {
- return new DateTime(date).
- withHourOfDay(0).
- withMinuteOfHour(0).
- withSecondOfMinute(0).
- withMillisOfSecond(0).toDate();
- }
- /**
- * Get temporal date instance of the current {@code datetime}.
- * <p>
- * This will truncate minute, seconds and milliseconds from the given date.
- *
- * @return Temporal date
- */
- public static Date nowYMDH() {
- return tempoYMDH(new Date());
- }
- /**
- * Get temporal date instance.
- * <p>
- * This will truncate minute, seconds and milliseconds from the given date.
- *
- * @param date A date
- * @return Temporal date
- */
- public static Date tempoYMDH(Date date) {
- return new DateTime(date).
- withMinuteOfHour(0).
- withSecondOfMinute(0).
- withMillisOfSecond(0).toDate();
- }
- /**
- * Get temporal date instance of the current {@code datetime}.
- * <p>
- * This will truncate seconds and milliseconds from the given date.
- *
- * @return Temporal date
- */
- public static Date tempoYMDHM() {
- return tempoYMDHM(new Date());
- }
- /**
- * Get temporal date instance.
- * <p>
- * This will truncate seconds and milliseconds from the given date.
- *
- * @param date A date
- * @return Temporal date
- */
- public static Date tempoYMDHM(Date date) {
- return new DateTime(date).withSecondOfMinute(0).withMillisOfSecond(0).toDate();
- }
- /**
- * Convert duration to hours.
- *
- * @param duration Duration of time
- * @return Hours of time
- */
- public static BigDecimal toHrBigDecimal(final BigDecimal duration) {
- BigDecimal result = BigDecimal.ZERO.setScale(1);
- try {
- result = duration.divide(
- new BigDecimal("3600000"),
- BigDecimal.ROUND_HALF_UP)
- .setScale(1, RoundingMode.HALF_UP);
- } catch (Exception e) {
- LOGGER.error("Cause: {}", e.toString());
- }
- return result;
- }
- /**
- * Convert duration to minutes.
- *
- * @param duration Duration of time
- * @return Minutes of time
- */
- public static int toMinuteInt(BigDecimal duration) {
- int result = 0;
- try {
- result = duration.divide(
- new BigDecimal("60000"),
- BigDecimal.ROUND_DOWN)
- .remainder(new BigDecimal("60")).intValue();
- } catch (Exception e) {
- LOGGER.error("Cause: {}", e.toString());
- }
- return result;
- }
- /**
- * Converts time into different {@link TimeUnit}.
- * <p>
- * Useful tool for converting a time into different units.
- * <br /> <br />
- * Example: <br />
- * <blockquote> {@code convert(60, TimeUnit.MINUTE, TimeUnit.SECONDS)} will
- * return {@code 1} because 60 seconds was converted to minute.
- * </blockquote>
- *
- * @param aTime Time of any unit
- * @param convertTo Time unit conversion result
- * @param convertFrom Time unit of the given {@code aTime}
- * @return Converted time which time unit is based on the given
- * {@code convertTo} value of {@link TimeUnit}
- */
- public static long convert(final long aTime, TimeUnit convertTo, TimeUnit convertFrom) {
- return convertTo.convert(aTime, convertFrom);
- }
- /**
- * Simple unit conversion.
- * <p>
- * <blockquote>
- * Note: <i>fraction is currently not supported for now.</i>
- * </blockquote>
- *
- * @param seconds Seconds in time
- * @return Converted millis from seconds (seconds->millis)
- */
- public static long secondsToNano(final long seconds) {
- return TimeUnit.NANOSECONDS.convert(seconds, TimeUnit.SECONDS);
- }
- /**
- * Simple unit conversion.
- * <p>
- * <blockquote>
- * Note: <i>fraction is currently not supported for now.</i>
- * </blockquote>
- *
- * @param seconds Seconds in time
- * @return Converted nanoseconds from seconds (seconds->nanos)
- */
- public static long secondsToMillis(final long seconds) {
- return TimeUnit.MILLISECONDS.convert(seconds, TimeUnit.SECONDS);
- }
- /**
- * Simple unit conversion.
- * <p>
- * <blockquote>
- * Note: <i>fraction is currently not supported for now.</i>
- * </blockquote>
- *
- * @param minute Minutes in time
- * @return Converted millis from minute (minute->millis)
- */
- public static long minuteToMillis(final long minute) {
- return TimeUnit.MILLISECONDS.convert(minute, TimeUnit.MINUTES);
- }
- /**
- * Simple unit conversion.
- * <p>
- * <blockquote>
- * Note: <i>fraction is currently not supported for now.</i>
- * </blockquote>
- *
- * @param minute Minutes in time
- * @return Converted seconds from minutes (minutes->seconds)
- */
- public static long minuteToSeconds(final long minute) {
- return TimeUnit.SECONDS.convert(minute, TimeUnit.MINUTES);
- }
- /**
- * Simple unit conversion.
- * <p>
- * <blockquote>
- * Note: <i>fraction is currently not supported for now.</i>
- * </blockquote>
- *
- * @param hour Hour in time
- * @return Converted millis from hour (hours->millis)
- */
- public static long hourToMillis(final long hour) {
- return TimeUnit.MILLISECONDS.convert(hour, TimeUnit.HOURS);
- }
- /**
- * Simple unit conversion.
- * <p>
- * <blockquote>
- * Note: <i>fraction is currently not supported for now.</i>
- * </blockquote>
- *
- * @param hour Hour in time
- * @return Converted seconds from hour (hours->seconds)
- */
- public static long hourToSeconds(final long hour) {
- return TimeUnit.SECONDS.convert(hour, TimeUnit.HOURS);
- }
- /**
- * Simple unit conversion.
- * <p>
- * <blockquote>
- * Note: <i>fraction is currently not supported for now.</i>
- * </blockquote>
- *
- * @param hour Hour in time
- * @return Converted minute from hour (hours->minute)
- */
- public static long hourToMinute(final long hour) {
- return TimeUnit.MINUTES.convert(hour, TimeUnit.HOURS);
- }
- /**
- * Convert milliseconds to date format.
- * <p>
- * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day, 10 hrs
- * 17 mins, 36 sec </b> </i>
- *
- * @param millis Milliseconds of time
- * @return Formatted date and time
- * @see Times#toDateWord(long) toDateWord() is a good alternative
- */
- public static String toDate(final long millis) {
- long _millis = millis;
- final long SECOND = 1000;
- final long MINUTE = 60 * SECOND;
- final long HOUR = 60 * MINUTE;
- final long DAY = 24 * HOUR;
- final StringBuffer text = new StringBuffer();
- if (_millis > DAY) {
- final long _day = _millis / DAY;
- text.append(_day).append(_day > 1 ? " days" : " day");
- _millis = _millis % DAY;
- }
- if (_millis > HOUR) {
- text.append(", ");
- final long _hour = _millis / HOUR;
- text.append(_hour).append(_hour > 1 ? " hrs" : " hr");
- _millis = _millis % HOUR;
- }
- if (_millis > MINUTE) {
- text.append(", ");
- final long _minute = _millis / MINUTE;
- text.append(_minute).append(_minute > 1 ? " mins" : " min");
- _millis = _millis % MINUTE;
- }
- if (_millis > SECOND) {
- text.append(", ");
- text.append(_millis / SECOND).append("sec");
- }
- return text.toString();
- }
- /**
- * Convert milliseconds to date worded format.
- * <p>
- * Example:
- * <pre><i> millis = <b> 123456789 </b> will result to <b> 1 day, 10 hrs
- * 17 mins, 36 sec </b> </i></pre>
- * <br/ >
- * <i> Note: Any caught exception will return {@code null}. Also a negative
- * millis value will immediately return {@code null}.</i>
- *
- * @param date {@link Date}
- * @return Formatted date and time
- */
- public static String toDateWord(final Date date) {
- return toDateWord(date.getTime());
- }
- /**
- * Convert milliseconds to date worded format.
- * <p>
- * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day, 10 hrs
- * 17 mins, 36 sec </b> </i>
- * <br/ >
- * <i> Note: Any caught exception will return {@code null}. Also a negative
- * millis value will immediately return {@code null}.</i>
- *
- * @param millis A time in millis
- * @return Formatted date and time.
- */
- public static String toDateWord(final long millis) {
- if (millis < 0) {
- LOGGER.error("Invalid millis! It must be a valid non-negative numerical value!");
- return null;
- }
- return new PeriodFormatterBuilder()
- .appendYears() // Year
- .appendSuffix(" year", " years")
- .appendSeparator(", ")
- .appendDays() // Day
- .appendSuffix(" day", " days")
- .appendSeparator(", ")
- .appendHours() // Hour
- .appendSuffix(" hr", " hrs")
- .appendSeparator(", ")
- .appendMinutes() // Min
- .appendSuffix(" min", " min")
- .appendSeparator(", ")
- .appendSeconds() // Sec
- .appendSuffix(" sec")
- .toFormatter().print(new Period(millis).normalizedStandard(
- PeriodType.standard()
- .withMonthsRemoved()
- .withWeeksRemoved()
- .withMillisRemoved()));
- }
- /**
- * Convert milliseconds to date colon format.
- * <p>
- * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day,
- * 10:17:36 </b> </i>
- * <br/ >
- * <i> Note: Any caught exception will return {@code null}. Also a negative
- * millis value will immediately return {@code null}.</i>
- *
- * @param date {@link Date}
- * @return Formatted date and time
- */
- public static String toDateColon(final Date date) {
- return toDateColon(date.getTime());
- }
- /**
- * Convert milliseconds to date colon format.
- * <p>
- * Example: <i> millis = <b> 123456789 </b> will result to <b> 1 day,
- * 10:17:36 </b> </i>
- * <br/ >
- * <i> Note: Any caught exception will return {@code null}. Also a negative
- * millis value will immediately return {@code null}.</i>
- *
- * @param millis A time in millis
- * @return Formatted date and time
- */
- public static String toDateColon(final long millis) {
- if (millis < 0) {
- LOGGER.error("Invalid millis! It must be a valid non-negative numerical value!");
- return null;
- }
- return new PeriodFormatterBuilder()
- .printZeroAlways() // Hour
- .minimumPrintedDigits(2)
- .maximumParsedDigits(3)
- .appendHours()
- .appendSeparator(":")
- .printZeroAlways() // Minute
- .minimumPrintedDigits(2)
- .appendMinutes()
- .appendSeparator(":")
- .printZeroAlways() // Sec
- .minimumPrintedDigits(2)
- .appendSeconds()
- .toFormatter().print(new Period(millis).normalizedStandard(
- PeriodType.standard()
- .withYearsRemoved()
- .withMonthsRemoved()
- .withWeeksRemoved()
- .withDaysRemoved()
- .withMillisRemoved()));
- }
- /**
- * Format the current date (today) to String format.
- * <p>
- * Customize the format of the current Date instance based on your specified
- * date format. This will
- *
- * <blockquote>
- * <b>Example:</b>
- * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
- * "10/23/1992 09:09:09 AM"
- * </blockquote>
- * <br /><br />
- * <i> Note: Any caught exception will return {@code null}. Also a
- * {@code null} {@code pattern} will immediately return {@code null}.</i>
- *
- * @param pattern Your own date format
- * @return Formatted date based on the specified date
- */
- public static synchronized String toDateFormat(final String pattern) {
- if (Is.empty(pattern)) {
- LOGGER.info("Date pattern is null or empty! Returning null...");
- return null;
- }
- return toDateFormat(new Date(), pattern);
- }
- /**
- * Format date to String format.
- * <p>
- * Customize the format of your Date instance based on your specified date
- * format. This will
- *
- * <blockquote>
- * <b>Example:</b>
- * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
- * "10/23/1992 09:09:09 AM"
- * </blockquote>
- * <br /><br />
- * <i> Note: Any caught exception will return {@code null}. Also a
- * {@code null} {@code date} value will immediately return {@code null}.</i>
- *
- * @param date Date you want to changed format
- * @param pattern Your own date format
- * @return Formatted date based on the specified date
- */
- public static String toDateFormat(final DateTime date, final String pattern) {
- String result = null;
- if (date == null) {
- LOGGER.info("Null value! Returning null...");
- return result;
- }
- try {
- result = date.toString(pattern, Locale.getDefault());
- } catch (IllegalArgumentException e) {
- LOGGER.error("Cause: {}", e.toString());
- }
- return result;
- }
- /**
- * Format date to String format.
- * <p>
- * Customize the format of your Date instance based on your specified date
- * format. This will
- *
- * <blockquote>
- * <b>Example:</b>
- * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
- * "10/23/1992 09:09:09 AM"
- * </blockquote>
- * <br /><br />
- * <i> Note: Any caught exception will return {@code null}. Also a
- * {@code null} {@code date} value will immediately return {@code null}.</i>
- *
- * @param date Date you want to changed format
- * @param pattern Your own date format
- * @return Formatted date based on the specified date, {@code null} if an
- * exception was caught
- */
- public static synchronized String toDateFormat(final Date date, final String pattern) {
- String result = null;
- if (date == null) {
- LOGGER.info("Null value! Returning null...");
- return result; // Return immediately
- }
- try {
- result = new DateTime(date).toString(pattern, Locale.getDefault());
- } catch (IllegalArgumentException e) {
- LOGGER.error("Cause: {}", e.toString());
- }
- return result;
- }
- /**
- * Parses text from the beginning of the given string to produce a date.
- * <p>
- * The method may not use the entire text of the given string.
- *
- * <blockquote>
- * <b>Example:</b>
- * <br /> {@code pattern = (mm/dd/yyyy hh:mm:ss a)} will result to
- * "10/23/1992 09:09:09 AM"
- * </blockquote>
- * <br /><br />
- * <i> Note: Any caught exception will return null. </i>
- *
- * @param date Date you want to changed format
- * @param pattern Your own date format
- * @param dflt Default value
- * @return Parsed Date instance, {@code dflt} if ParseExceptin was caught
- */
- public static Date toDateFormat(Date date, String pattern, Date dflt) {
- try {
- return new SimpleDateFormat(pattern).parse(toDateFormat(date, pattern));
- } catch (ParseException e) {
- LOGGER.debug("Formatting Date failed - Cause: {} - Returning dflt value ({})", e.toString(), dflt);
- return dflt;
- }
- }
- /**
- * Convert duration to hours.
- *
- * @param duration Duration of time
- * @return Hours of time
- */
- public static long durationToHourInt(BigDecimal duration) {
- return duration.divide(new BigDecimal("3600000"), BigDecimal.ROUND_DOWN).longValue();
- }
- /**
- * Set the time of the given date to the given time-format string. For
- * Example, the date you've given is (1992-10-23) and the time you've given
- * is (11:40am), the date you'll get is 1992-10-23 11:40.
- *
- * @param date Any valid date
- * @param time Any valid time format
- * @return Date with the given time. Will return the same date if an
- * exception was caught.
- */
- public static Date getDateWithTime(Date date, String time) {
- Date result = date;
- try {
- final DateTime datetime = new DateTime(date);
- int hour = Integer.parseInt(time.substring(0, 1));
- int minute = Integer.parseInt(time.substring(3, 4));
- if (time.substring(5).equalsIgnoreCase("pm")) {
- hour += 12;
- }
- result = datetime.withTime(hour, minute, 0, 0).toDate();
- } catch (NumberFormatException e) {
- LOGGER.error("Cause: {}", e.toString());
- }
- return result;
- }
- /**
- * Gets the day of week name.
- *
- * @param date the basis date.
- * @return the name of the day of week of the date parameter.
- */
- public static String getDayOfWeekName(Date date) {
- final int dayOfWeek = getDayOfWeek(date);
- return (dayOfWeek == 1) ? "Monday"
- : (dayOfWeek == 2) ? "Tuesday"
- : (dayOfWeek == 3) ? "Wednesday"
- : (dayOfWeek == 4) ? "Thursday"
- : (dayOfWeek == 5) ? "Friday"
- : (dayOfWeek == 6) ? "Saturday"
- : (dayOfWeek == 7) ? "Sunday" : "";
- }
- /**
- * Gets the day of week in integer.
- *
- * @param date Date basis to get the day of week.
- * @return The {@code nth} position of the date day of week
- */
- public static int getDayOfWeek(Date date) {
- return new DateTime(date).getDayOfWeek();
- }
- /**
- * Compares DateTime's month, day and year.
- * <p>
- * Seconds and milliseconds are ignored in this comparator.
- *
- * @param dt1 A DateTime
- * @param dt2 Another DateTime
- * @return True if both DateTime has equal month, day and year, otherwise
- * false
- */
- public static boolean compareDateTime(DateTime dt1, DateTime dt2) {
- return (dt1.getMonthOfYear() == dt2.getMonthOfYear())
- && (dt1.getDayOfMonth() == dt2.getDayOfMonth())
- && (dt1.getYear() == dt2.getYear());
- }
- /**
- * This puts zero in from of the time-format string.
- * <p>
- * It will return the same string if there's already a zero in front.
- *
- * @param time A time
- * @return The time-format {@link String}
- */
- public static String putZero(String time) {
- return time.startsWith("0") ? "0" + time : time;
- }
- /**
- * Get day today in instance of String.
- * <p>
- *
- * <blockquote>
- * <b>Example:</b>
- * "Monday", "Friday"
- * </blockquote>
- *
- * @return Day today.
- */
- public static String getDay() {
- return toDateFormat(new Date(), "EEEE");
- }
- /**
- * Get date today in instance of String according to your own format.
- * <p>
- * <blockquote>
- * <b>Example:</b>
- * pattern = (mm/dd/yyyy) will result to "10231992"
- * </blockquote>
- * <i>
- * Note: Any caught exception such as NumberFormatException will return 0,
- * so you may know from your top-level class that there was caught
- * exception.
- * </i>
- *
- * @param pattern Your own date format
- * @return Date today according to your format, then 0 if there's a caught
- * exception.
- */
- public static int getDate(String pattern) {
- return Numbers.get(toDateFormat(new Date(), pattern).replaceAll("\\D", ""));
- }
- /**
- * Get the current month.
- * <p>
- * Used the pattern <code>"MM"</code> pattern to get the month.
- *
- * @return The current month, zero (0) if an error occur
- */
- public static int getMonth() {
- return Numbers.get(toDateFormat("MM"));
- }
- /**
- * Get the current year.
- * <p>
- * Used the pattern <code>"YY"</code> pattern to get the year.
- *
- * @return The current year, zero (0) if an error occur
- */
- public static int getYearYY() {
- return Numbers.get(toDateFormat("YY"));
- }
- /**
- * Get the current year.
- * <p>
- * Used the pattern <code>"yyyy"</code> pattern to get the year.
- *
- * @return The current year, zero (0) if an error occur
- */
- public static int getYearYYYY() {
- return Numbers.get(toDateFormat("yyyy"));
- }
- /**
- * Get the hour time from the given {@code dateTime}.
- * <p>
- * Datetime format will based on the given {@code pattern}. Format or
- * pattern should have "hh" or "HH" to get the hour time.
- *
- * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
- * 21:30)
- * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
- * @param hour24Format 24-hour base {@code dateTime} (eg. 23:59)?
- * @return If hour24Format is true, returns hour in 24-hour based time
- * format, otherwise 12-hour based format
- * @see Times#getHrFromDateStr(java.lang.String, java.lang.String, boolean)
- *
- */
- public static int getHrFromDate(String dateTime, String pattern, boolean hour24Format) {
- return Numbers.get(
- getHrFromDateStr(dateTime, pattern, hour24Format),
- 0);
- }
- /**
- * Get the hour time from the given {@code dateTime}.
- * <p>
- * Datetime format will based on the given {@code pattern}. Format or
- * pattern should have "hh" or "HH" to get the hour time.
- *
- * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
- * 21:30)
- * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
- * @param hour24Format 24-hour base {@code dateTime} (eg. 23:59)?
- * @return If hour24Format is true, returns hour in 24-hour based time
- * format, otherwise 12-hour based format
- * @see Times#getHrFromDate(java.lang.String, java.lang.String, boolean)
- */
- public static String getHrFromDateStr(String dateTime, String pattern, boolean hour24Format) {
- return DateTimeFormat.forPattern(pattern).
- parseDateTime(dateTime).
- toString(hour24Format ? "HH" : "hh");
- }
- /**
- * Get the minute time from the given {@code dateTime}.
- * <p>
- * Datetime format will based on the given {@code pattern}. Format or
- * pattern should have "mm" to get the minute time. Don't get confuse to
- * format "MM" and "mm" as the uppercase format is for month not minute.
- *
- * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
- * 21:30)
- * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
- * @return Minute value
- * @see Times#getHrFromDate(java.lang.String, java.lang.String, boolean)
- */
- public static int getMinFromDate(String dateTime, String pattern) {
- return Numbers.get(getMinFromDateStr(dateTime, pattern), 0);
- }
- /**
- * Get the minute time from the given {@code dateTime}.
- * <p>
- * Datetime format will based on the given {@code pattern}. Format or
- * pattern should have "mm" to get the minute time. Don't get confuse to
- * format "MM" and "mm" as the uppercase format is for month not minute.
- *
- *
- * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
- * 21:30)
- * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
- * @return Minute value
- * @see Times#getHrFromDate(java.lang.String, java.lang.String, boolean)
- * value
- */
- public static String getMinFromDateStr(String dateTime, String pattern) {
- return DateTimeFormat.forPattern(pattern).parseDateTime(dateTime).
- toString("mm");
- }
- /**
- * Converts the given {@code dateTime} with type of {@code String} to
- * instance of {@link DateTime}.
- * <p>
- * The given {@code dateTime} should be appropriate to the given
- * {@code pattern}.
- * <br />
- * Note: <i> Format will not be retain if {@link DateTime#toString()} was
- * invoke, use {@link DateTime#toString(java.lang.String)} instead to have
- * your own date format. </i>
- *
- * @param dateTime A {@code Date} in type of {@code String} (eg. 09:30,
- * 21:30)
- * @param pattern Date format or pattern (eg. hh:mm, HH:mm)
- * @return Instance of {@link DateTime} from the given {@code dateTime}
- */
- public static DateTime toDateTime(String dateTime, String pattern) {
- try {
- return DateTimeFormat.forPattern(pattern).parseDateTime(dateTime);
- } catch (Exception e) {
- LOGGER.error("Cause: {}", e.toString());
- return null;
- }
- }
- /**
- * Converts the given {@code dateTime} with type of {@code String} to
- * instance of {@link Date}.
- * <p>
- * The given {@code dateTime} should be appropriate to the given
- * {@code pattern}.
- * <br />
- * Note: <i> Format will not be retain if {@link Date#toString()} was
- * invoke, use {@link DateTime#toString(java.lang.String)} instead to have
- * your own date format. </i>
- *
- * @param dateTime A {@code Date} in type of {@code String}
- * @param pattern Date format or pattern
- * @return Instance of {@link Date} from the given {@code dateTime}
- */
- public static Date toDate(String dateTime, String pattern) {
- final DateTime result = toDateTime(dateTime, pattern);
- return Is.nil(result) ? null : result.toDate();
- }
- /**
- * Set the time of date given.
- * <p>
- * The given {@code time} should be in format of "HH:mm" or "hh:mm".
- *
- * @param date Date to be modified
- * @param time Time to be evaluated
- * @param hour24Format 24-hour base {@code dateTime} (eg. 23:59)?
- * @return Instance of {@code java.util.Date} with the given time
- */
- public static Date setTimeFromDate(Date date, String time, boolean hour24Format) {
- final String format = (hour24Format) ? "HH:mm" : "hh:mm";
- return new DateTime(date).
- withHourOfDay(Times.getHrFromDate(time, format, hour24Format)).
- withMinuteOfHour(Times.getMinFromDate(time, format)).
- toDate();
- }
- /**
- * Gets the hour in the given date.
- *
- * @param date Date where the hour will be come from
- * @return Hour of the given date
- */
- public static int getHrFromDate(Date date) {
- return new DateTime(date).getHourOfDay();
- }
- /**
- * Adds days in the given date.
- *
- * @param date Date to be modified
- * @param years Number of years to be added
- * @return Instance of {@code java.util.Date} with years added.
- */
- public static Date plusYear(Date date, int years) {
- return new DateTime(date).plusYears(years).toDate();
- }
- /**
- * Subtracts days in the given date.
- *
- * @param date Date to be modified
- * @param years Number of year to be subtracted
- * @return Instance of {@code java.util.Date} with years subtracted
- */
- public static Date minusYear(Date date, int years) {
- return new DateTime(date).minusYears(years).toDate();
- }
- /**
- * Adds days in the given date.
- *
- * @param date Date to be modified
- * @param weeks Number of weeks to be added
- * @return Instance of {@code java.util.Date} with weeks added.
- */
- public static Date plusWeek(Date date, int weeks) {
- return new DateTime(date).plusWeeks(weeks).toDate();
- }
- /**
- * Subtracts days in the given date.
- *
- * @param date Date to be modified
- * @param weeks Number of weeks to be subtracted
- * @return Instance of {@code java.util.Date} with weeks subtracted
- */
- public static Date minusWeek(Date date, int weeks) {
- return new DateTime(date).minusWeeks(weeks).toDate();
- }
- /**
- * Adds days in the given date.
- *
- * @param date Date to be modified
- * @param days Number of days to be added
- * @return Instance of {@code java.util.Date} with days added.
- */
- public static Date plusDay(Date date, int days) {
- return new DateTime(date).plusDays(days).toDate();
- }
- /**
- * Subtracts days in the given date.
- *
- * @param date Date to be modified
- * @param days Number of days to be subtracted
- * @return Instance of {@code java.util.Date} with days subtracted
- */
- public static Date minusDay(Date date, int days) {
- return new DateTime(date).minusDays(days).toDate();
- }
- /**
- * Adds hours in the given date.
- *
- * @param date Date to be modified
- * @param hours Number of hours to be added
- * @return Instance of {@code java.util.Date} with hours added
- */
- public static Date plusHour(Date date, int hours) {
- return new DateTime(date).plusHours(hours).toDate();
- }
- /**
- * Subtracts hours in the given date.
- *
- * @param date Date to be modified
- * @param hours Number of hours to be subtracted
- * @return Instance of {@code java.util.Date} with hours subtracted
- */
- public static Date minusHour(Date date, int hours) {
- return new DateTime(date).minusHours(hours).toDate();
- }
- /**
- * Adds minutes in the time of the date.
- *
- * @param date Date to be modified
- * @param minutes Number of minutes to be added
- * @return Instance of {@code java.util.Date} with minutes added
- */
- public static Date plusMinute(Date date, int minutes) {
- return new DateTime(date).plusMinutes(minutes).toDate();
- }
- /**
- * Subtracts minutes in the time of the date.
- *
- * @param date Date to be modified
- * @param minutes Number of minutes to be subtracted
- * @return Instance of {@code java.util.Date} with minutes subtracted
- */
- public static Date minusMinute(Date date, int minutes) {
- return new DateTime(date).minusMinutes(minutes).toDate();
- }
- /**
- * Adds minutes in the time of the date.
- *
- * @param date Date to be modified
- * @param minutes Number of minutes to be added
- * @return Instance of {@code java.util.Date} with minutes added
- */
- public static Date plusSecond(Date date, int minutes) {
- return new DateTime(date).plusSeconds(minutes).toDate();
- }
- /**
- * Subtracts minutes in the time of the date.
- *
- * @param date Date to be modified
- * @param minutes Number of minutes to be subtracted
- * @return Instance of {@code java.util.Date} with minutes subtracted
- */
- public static Date minusSecond(Date date, int minutes) {
- return new DateTime(date).minusSeconds(minutes).toDate();
- }
- /**
- * Gets the seconds difference of the two dates.
- * <p>
- * The second date must always be the larger to obtain a positive value.
- *
- * @param firstDate First date or in subtraction, the subtrahend
- * @param secondDate Second date or in subtraction, the minuend
- * @return Seconds difference of the two dates
- */
- public static int getSecDiff(Date firstDate, Date secondDate) {
- return Numbers.toInt(new Duration(firstDate.getTime(), secondDate.getTime()).getStandardSeconds());
- }
- /**
- * Time format for
- * {@link Times#convertTime(java.lang.String, my.jutils.Times.TimeFormat)}.
- */
- public static enum TimeFormat {
- /**
- * 12-hour format.
- */
- Twelve,
- /**
- * 24-hour format.
- */
- TwentyFour;
- }
- /**
- * Converts time based on the given format.
- *
- * @param time Time to be converted {@code (Eg. 9:00am or 19:00)}
- * @param format Output format of the time from {@link TimeFormat}
- * @return Formatted time, otherwise {@code empty String} if the
- * {@code time} given was null or empty
- */
- public static String convertTime(String time, TimeFormat format) {
- if (Is.empty(time)) {
- return "";
- }
- String currentFormat;
- String newFormat;
- String result = "";
- if (TimeFormat.Twelve == format) {
- currentFormat = "HH:mm";
- newFormat = "hh:mma";
- } else { // If time convert to 24-hour format
- newFormat = "HH:mm";
- currentFormat = "hh:mma";
- }
- try {
- result = new SimpleDateFormat(newFormat).
- format(new SimpleDateFormat(currentFormat).parse(time));
- } catch (ParseException e) {
- LOGGER.error("Cause: {}", e.toString());
- }
- return result;
- }
- /**
- * Converts the native java date ({@link Date}) to SQL date instance.
- *
- * @param date instance of {@link Date}
- * @return instance of SQL date otherwise if date is null, will return null
- */
- public static java.sql.Date toSQLDate(java.util.Date date) {
- return new java.sql.Date(date.getTime());
- }
- /**
- * Converts the native java date ({@link Date}) to SQL timestamp instance.
- *
- * @param date instance of {@link Date}
- * @return instance of SQL timestamp otherwise if date is null, will return
- * null
- */
- public static java.sql.Timestamp toSQLTimeStamp(java.util.Date date) {
- return new java.sql.Timestamp(date.getTime());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment