Java tutorial
/* * Copyright 2004 Senunkan Shinryuu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.latticesoft.util.common; import java.text.SimpleDateFormat; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; import java.sql.Timestamp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public final class DateUtil { private static final Log log = LogFactory.getLog(DateUtil.class); public static final DateFormat FORMAT_YEAR = new SimpleDateFormat("yyyy"); public static final DateFormat FORMAT_MONTH = new SimpleDateFormat("MM"); public static final DateFormat FORMAT_DAY = new SimpleDateFormat("dd"); public static final DateFormat FORMAT_HOUR = new SimpleDateFormat("HH"); public static final DateFormat FORMAT_MINUTE = new SimpleDateFormat("mm"); public static final DateFormat FORMAT_SECOND = new SimpleDateFormat("ss"); public static final DateFormat FORMAT_MILLISECOND = new SimpleDateFormat("SSS"); public static final DecimalFormat FORMAT_DIGIT4 = new DecimalFormat("0000"); public static final DecimalFormat FORMAT_DIGIT3 = new DecimalFormat("000"); public static final DecimalFormat FORMAT_DIGIT2 = new DecimalFormat("00"); public static final DateFormat FMT_FLOAT_TO_DATE = new SimpleDateFormat("yyyyMMdd"); public static final DateFormat FMT_DATE_TO_FLOAT = new SimpleDateFormat("yyMMdd"); public static final String[] MONTH = { "", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }; public static final String[] MONTH_FULL = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; /** * Parse the string into a util date * @param format the date format * @param value the string to be parsed * @return the java util date */ public static Date parseUtilDate(String format, String value) { if (format == null || value == null) { return null; } try { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.parse(value); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } return null; } /** * Parses the string into a timestamp. * @param s the target string * @param format the date format * @return the timestamp parsed */ public static Timestamp parseTimestamp(String format, String value) { Date d = DateUtil.parseUtilDate(format, value); Timestamp ts = null; if (d != null) { ts = new Timestamp(d.getTime()); } return ts; } /** * Parses the string into a SQL Date. * @param s the target string * @param format the date format * @return the SQL date parsed */ public static java.sql.Date parseSQLDate(String format, String value) { Date d = DateUtil.parseUtilDate(value, format); java.sql.Date sqld = null; if (d != null) { sqld = new java.sql.Date(d.getTime()); } return sqld; } /** * Parses a util date from int input * @param year the year * @param month the month * @param day the day * @returns a java.util.Date */ public static Date parseUtilDate(int year, int month, int day) { return parseUtilDate(year, month, day, 0, 0, 0, 0); } /** * Parses a util date from int input * @param year the year * @param month the month * @param day the day * @param hour what hour * @param minute what minute * @param second what second * @param millis what millisecond * @returns a java.util.Date */ public static Date parseUtilDate(int year, int month, int day, int hour, int minute, int second, int millis) { if (year < 0 || month < 0 || month > 12 || day < 0 || day > 31) { return null; } if ((hour < 0 || hour > 24 || day < 0 && day > 31)) { return null; } try { StringBuffer sb = new StringBuffer(); sb.append(FORMAT_DIGIT4.format(year)); sb.append(FORMAT_DIGIT2.format(month)); sb.append(FORMAT_DIGIT2.format(day)); sb.append(FORMAT_DIGIT2.format(hour)); sb.append(FORMAT_DIGIT2.format(minute)); sb.append(FORMAT_DIGIT2.format(second)); sb.append(FORMAT_DIGIT3.format(millis)); return DateUtil.parseUtilDate("yyyyMMddHHmmssSSS", sb.toString()); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } return null; } /** * Parses the individual date component into a SQL date */ public static java.sql.Date parseSqlDate(int year, int month, int day, int hour, int minute, int second, int millis) { Date d = parseUtilDate(year, month, day, hour, minute, second, millis); return new java.sql.Date(d.getTime()); } /** * Parses the individual date component into a Timestamp */ public static Timestamp parseTimestamp(int year, int month, int day, int hour, int minute, int second, int millis) { Date d = parseUtilDate(year, month, day, hour, minute, second, millis); return new java.sql.Timestamp(d.getTime()); } /** * Formats a date into a string using a specified format. * @param date the date to be formatted * @param dateFormat the format to format it * @return null if either of the input is null or invalid inputs. * Otherwise the date format in string is returned. */ public static String formatDate(String format, Date date) { if (format == null || date == null) { return null; } try { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } return null; } /** * Formats a date by a year month day input * @param format the date format * @param year the year * @param month the month * @param day the day */ public static String formatDate(String format, int year, int month, int day) { if (format == null || year < 0 || month <= 0 || day <= 0 || month > 12 || day > 31) { return null; } try { Date d = DateUtil.parseUtilDate(year, month, day); return DateUtil.formatDate(format, d); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } return null; } /** * Get the current date with all the time component set to zero */ public static Date getCurrentUtilDate() { int year = DateUtil.getCurrentYear(); int month = DateUtil.getCurrentMonth(); int day = DateUtil.getCurrentDay(); StringBuffer sb = new StringBuffer(); sb.append(year); if (month < 10) { sb.append("0"); } sb.append(month); if (day < 10) { sb.append("0"); } sb.append(day); return DateUtil.parseUtilDate("yyyyMMdd", sb.toString()); } /** Gets the current SQL Date */ public static java.sql.Date getCurrentSQLDate() { return new java.sql.Date(System.currentTimeMillis()); } /** Gets the current timestamp */ public static Timestamp getCurrentTimestamp() { return new Timestamp(System.currentTimeMillis()); } public static int getCurrentYear() { Date date = DateUtil.getCurrentTimestamp(); return DateUtil.getYear(date); } public static int getCurrentMonth() { Date date = DateUtil.getCurrentTimestamp(); return DateUtil.getMonth(date); } public static int getCurrentDay() { Date date = DateUtil.getCurrentTimestamp(); return DateUtil.getDay(date); } public static int getCurrentHour() { Date date = DateUtil.getCurrentTimestamp(); return DateUtil.getHour(date); } public static int getCurrentMinute() { Date date = DateUtil.getCurrentTimestamp(); return DateUtil.getMinute(date); } public static int getCurrentSecond() { Date date = DateUtil.getCurrentTimestamp(); return DateUtil.getSecond(date); } public static int getCurrentMillisecond() { Date date = DateUtil.getCurrentTimestamp(); return DateUtil.getMilliSecond(date); } private static int getDateComponent(DateFormat df, Date src) { try { String s = df.format(src); return Integer.parseInt(s); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } } return 0; } public static int getYear(Date date) { return getDateComponent(DateUtil.FORMAT_YEAR, date); } public static int getMonth(Date date) { return getDateComponent(DateUtil.FORMAT_MONTH, date); } public static int getDay(Date date) { return getDateComponent(DateUtil.FORMAT_DAY, date); } public static int getHour(Date date) { return getDateComponent(DateUtil.FORMAT_HOUR, date); } public static int getMinute(Date date) { return getDateComponent(DateUtil.FORMAT_MINUTE, date); } public static int getSecond(Date date) { return getDateComponent(DateUtil.FORMAT_SECOND, date); } public static int getMilliSecond(Date date) { return getDateComponent(DateUtil.FORMAT_MILLISECOND, date); } /** * Returns a int array of from date. The array contains * year, month, day, hour, minute, second, milliseconds in order * @param the date to be converted */ public static int[] getDateComponents(Date date) { int[] retVal = new int[7]; try { retVal[0] = Integer.parseInt(FORMAT_YEAR.format(date)); retVal[1] = Integer.parseInt(FORMAT_MONTH.format(date)); retVal[2] = Integer.parseInt(FORMAT_DAY.format(date)); retVal[3] = Integer.parseInt(FORMAT_HOUR.format(date)); retVal[4] = Integer.parseInt(FORMAT_MINUTE.format(date)); retVal[5] = Integer.parseInt(FORMAT_SECOND.format(date)); retVal[6] = Integer.parseInt(FORMAT_MILLISECOND.format(date)); } catch (Exception e) { for (int i = 0; i < retVal.length; i++) { retVal[i] = 0; } } return retVal; } /** * Returns a int array of from date. The array contains * year, month, day, hour, minute, second, milliseconds in order * @param the date to be converted */ public static TimePeriod getDateComponentsAsTimePeriod(Date date) { TimePeriod tp = new TimePeriod(); try { tp.setYear(Integer.parseInt(FORMAT_YEAR.format(date))); tp.setMonth(Integer.parseInt(FORMAT_MONTH.format(date))); tp.setDay(Integer.parseInt(FORMAT_DAY.format(date))); tp.setHour(Integer.parseInt(FORMAT_HOUR.format(date))); tp.setMinute(Integer.parseInt(FORMAT_MINUTE.format(date))); tp.setSecond(Integer.parseInt(FORMAT_SECOND.format(date))); tp.setMilli(Integer.parseInt(FORMAT_MILLISECOND.format(date))); } catch (Exception e) { } return tp; } /** * Returns the last day of the month * @param month the month * @param year the year */ public static int getLastDayOfMonthAsInt(int year, int month) { Date d = getLastDayOfMonth(year, month); return DateUtil.getDay(d); } /** * Returns the last day of the month * @param d the year and month */ public static Date getLastDayOfMonth(Date d) { return DateUtil.getLastDayOfMonth(DateUtil.getYear(d), DateUtil.getMonth(d)); } /** * Returns the last day of the month * @param month the month * @param year the year */ public static Date getLastDayOfMonth(int year, int month) { int day = 31; if (month > 7) { // after july day = (month % 2 == 0) ? 31 : 30; } else if (month <= 7 && month != 2) { // before july except feb day = (month % 2 == 0) ? 30 : 31; } else { // feburary cater for leap year day = 28; if (year % 4 == 0 && year % 100 != 0) { day = 29; } } return DateUtil.parseUtilDate(year, month, day); } /** * Returns the first day of the month * @param year which year * @param month which month */ public static Date getFirstDayOfMonth(int year, int month) { StringBuffer sb = new StringBuffer(); sb.setLength(0); sb.append(DateUtil.FORMAT_DIGIT4.format(year)); sb.append(DateUtil.FORMAT_DIGIT2.format(month)); sb.append("01000000"); return DateUtil.parseUtilDate("yyyyMMddHHmmss", sb.toString()); } /** * Returns the first day of the month * @param date the date */ public static Date getFirstDayOfMonth(Date date) { StringBuffer sb = new StringBuffer(); sb.setLength(0); sb.append(DateUtil.FORMAT_DIGIT4.format(DateUtil.getYear(date))); sb.append(DateUtil.FORMAT_DIGIT2.format(DateUtil.getMonth(date))); sb.append("01000000"); return DateUtil.parseUtilDate("yyyyMMddHHmmss", sb.toString()); } /** Returns the 1st day of current month. */ public static Date getFirstDayOfCurrentMonth() { int currYear = DateUtil.getCurrentYear(); int currMonth = DateUtil.getCurrentMonth(); return DateUtil.getFirstDayOfMonth(currYear, currMonth); } public static Date getLastDayOfCurrentMonth() { int currYear = DateUtil.getCurrentYear(); int currMonth = DateUtil.getCurrentMonth(); return DateUtil.getLastDayOfMonth(currYear, currMonth); } /** Returns the previous day. */ public static java.util.Date getPreviousDay() { java.util.Date d = getCurrentUtilDate(); java.util.Date retVal = null; retVal = addDay(d, -1); return retVal; } public static final int SUN = 0; public static final int MON = 1; public static final int TUE = 2; public static final int WED = 3; public static final int THU = 4; public static final int FRI = 5; public static final int SAT = 6; public static int getDayOfWeek(Date date) { if (date == null) return -1; String s = DateUtil.formatDate("EEE", date); if (s != null) { s = s.toUpperCase(); } if ("SUN".equals(s)) { return SUN; } else if ("MON".equals(s)) { return MON; } else if ("TUE".equals(s)) { return TUE; } else if ("WED".equals(s)) { return WED; } else if ("THU".equals(s)) { return THU; } else if ("FRI".equals(s)) { return FRI; } else if ("SAT".equals(s)) { return SAT; } return -1; } public static Date addyear(Date date, int year) { return addDate(date, year, 0, 0, 0, 0, 0, 0); } public static Date addMonth(Date date, int month) { return addDate(date, 0, month, 0, 0, 0, 0, 0); } public static Date addDay(Date date, int day) { return addDate(date, 0, 0, day, 0, 0, 0, 0); } public static Date addHour(Date date, int hour) { return addDate(date, 0, 0, 0, hour, 0, 0, 0); } public static Date addMinute(Date date, int minute) { return addDate(date, 0, 0, 0, 0, minute, 0, 0); } public static Date addSecond(Date date, int second) { return addDate(date, 0, 0, 0, 0, 0, second, 0); } public static Date addMillis(Date date, int millis) { return addDate(date, 0, 0, 0, 0, 0, 0, millis); } public static String addDateAsString(String format, Date d, int year, int month, int day, int hour, int minute, int second, int millis) { Date date = DateUtil.addUtilDate(d, year, month, day, hour, minute, second, millis); return DateUtil.formatDate(format, date); } public static Date addDate(Date src, int year, int month, int day, int hour, int minute, int second, int millis) { return addUtilDate(src, year, month, day, hour, minute, second, millis); } public static Date addDate(Date src, Date add) { int[] i = DateUtil.getDateComponents(add); if (i == null) return null; if (i.length < 7) return null; return DateUtil.addDate(src, i[0], i[1], i[2], i[3], i[4], i[5], i[6]); } public static Date addUtilDate(Date src, int year, int month, int day, int hour, int minute, int second, int millis) { if (src == null) return null; Calendar c = new GregorianCalendar(); c.setTime(src); c.add(Calendar.MILLISECOND, millis); c.add(Calendar.SECOND, second); c.add(Calendar.MINUTE, minute); c.add(Calendar.HOUR_OF_DAY, hour); c.add(Calendar.DAY_OF_MONTH, day); c.add(Calendar.MONTH, month); c.add(Calendar.YEAR, year); Date date = c.getTime(); if (src instanceof Timestamp) { return new Timestamp(date.getTime()); } if (src instanceof java.sql.Date) { return new java.sql.Date(date.getTime()); } return date; } public static Date addUtilDate(Date src, TimePeriod tp) { return addUtilDate(src, tp.getYear(), tp.getMonth(), tp.getDay(), tp.getHour(), tp.getMinute(), tp.getSecond(), tp.getMilli()); } public static java.sql.Date addSQLDate(java.sql.Date src, int year, int month, int day, int hour, int minute, int second, int millis) { Date d = addUtilDate(src, year, month, day, hour, minute, second, millis); java.sql.Date retVal = new java.sql.Date(d.getTime()); return retVal; } public static java.sql.Date addSQLDate(java.sql.Date src, TimePeriod tp) { return addSQLDate(src, tp.getYear(), tp.getMonth(), tp.getDay(), tp.getHour(), tp.getMinute(), tp.getSecond(), tp.getMilli()); } public static Timestamp addTimestamp(java.sql.Timestamp src, int year, int month, int day, int hour, int minute, int second, int millis) { Timestamp retVal = null; Date d = addUtilDate(src, year, month, day, hour, minute, second, millis); retVal = new Timestamp(d.getTime()); return retVal; } public static Timestamp addTimestamp(java.sql.Timestamp src, TimePeriod tp) { return addTimestamp(src, tp.getYear(), tp.getMonth(), tp.getDay(), tp.getHour(), tp.getMinute(), tp.getSecond(), tp.getMilli()); } /** * Return a date format as an integer (for those formattable as integer) * @param date the date to be converted * @param dateFormat the format of the date * @return the date part (as an int) */ public static int convertDateToInt(String dateFormat, java.util.Date date) { String s = DateUtil.formatDate(dateFormat, date); int retVal = 0; try { retVal = Integer.parseInt(s); } catch (Exception e) { } return retVal; } /** * Return a timestamp from an util date * @param date the date to be converted * @return the timestamp */ public static Timestamp convertDateToTimestamp(java.util.Date date) { Timestamp ts = null; try { ts = new Timestamp(date.getTime()); } catch (Exception e) { } return ts; } /** * Get a random timestamp */ public static Timestamp getRandomTimestamp(Timestamp start, Timestamp end) { Timestamp ts = null; if (start == null || end == null) { ts = new Timestamp(System.currentTimeMillis()); } else { long startTime = start.getTime(); long endTime = end.getTime(); long randomTime = NumeralUtil.getRandomLong(startTime, endTime); ts = new Timestamp(randomTime); } return ts; } /** * Checks if a particular time stamp is within the other 2 time stamp * Note that the date portion is ignored. * @param start start of zone * @param end end of zone * @param ts the time stamp to be checked * @return true if it is within the region */ public static boolean isWithinTimePeriod(Timestamp start, Timestamp end, Timestamp ts) { boolean b = false; if (start == null || end == null || ts == null) { return false; } // extract the time part String format = "HHmmss"; String t1 = DateUtil.formatDate(format, start); String t2 = DateUtil.formatDate(format, end); String tt = DateUtil.formatDate(format, ts); if (t2.compareTo(t1) > 0) { if (tt.compareTo(t1) >= 0 && t2.compareTo(tt) >= 0) { b = true; } } else { // t1 > t2 if ((tt.compareTo("235959") < 0 && tt.compareTo(t1) >= 0) || (tt.compareTo("000000") > 0 && tt.compareTo(t2) <= 0)) { b = true; } } return b; } /** * Checks if a particular date / time is within the other 2 date / time. * Note that the date portion is talen into consideration. * The * @param start start of zone * @param end end of zone * @param d the date to be checked * @return true if it is within the region */ public static boolean isWithinDateTimePeriod(Date start, Date end, Date d) { boolean retVal = false; if (start == null || end == null || d == null) { return false; } long l1 = start.getTime(); long l2 = end.getTime(); long l = d.getTime(); if (l2 > l1) { if (l >= l1 && l <= l2) { retVal = true; } } else { if (l >= l2 && l <= l1) { retVal = true; } } return retVal; } public static void main(String[] args) { /* Date d = DateUtil.parseTimestamp(2006, 1, 1, 23, 50, 12, 123); System.out.println(d); System.out.println(DateUtil.addDate(d, 1,0,0, 0,0,0, 0)); System.out.println(DateUtil.addDate(d, 0,1,0, 0,0,0, 0)); System.out.println(DateUtil.addDate(d, 0,0,1, 0,0,0, 0)); System.out.println(DateUtil.addDate(d, 0,0,0, 1,0,0, 0)); System.out.println(DateUtil.addDate(d, 0,0,0, 0,1,0, 0)); System.out.println(DateUtil.addDate(d, 0,0,0, 0,0,1, 0)); System.out.println(DateUtil.addDate(d, 0,0,0, 0,0,0, 1)); System.out.println("========="); Timestamp ts1 = DateUtil.getCurrentTimestamp(); Timestamp ts2 = DateUtil.addTimestamp(ts1, 0, 0, 0, 3, 0, 0, 0); Timestamp ts3 = DateUtil.getRandomTimestamp(ts1, ts2); System.out.println(ts1); System.out.println(ts2); System.out.println(ts3);//*/ System.out.println("=== time only ==="); Timestamp t1 = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 060000"); Timestamp t2 = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 180000"); Timestamp tt = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 123000"); System.out.println(t1 + " =< " + tt + " =< " + t2); System.out.println(DateUtil.isWithinTimePeriod(t1, t2, tt)); t1 = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 180000"); t2 = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 060000"); tt = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 123000"); System.out.println(t1 + " =< " + tt + " =< " + t2); System.out.println(DateUtil.isWithinTimePeriod(t1, t2, tt)); tt = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 190000"); System.out.println(t1 + " =< " + tt + " =< " + t2); System.out.println(DateUtil.isWithinTimePeriod(t1, t2, tt)); tt = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070604 000330"); System.out.println(t1 + " =< " + tt + " =< " + t2); System.out.println(DateUtil.isWithinTimePeriod(t1, t2, tt)); System.out.println("=== date time ==="); tt = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070604 000330"); System.out.println(t1 + " =< " + tt + " =< " + t2); System.out.println(DateUtil.isWithinDateTimePeriod(t1, t2, tt)); t1 = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 000000"); t2 = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 002359"); tt = DateUtil.parseTimestamp("yyyyMMdd HHmmss", "20070404 000330"); System.out.println(t1 + " =< " + tt + " =< " + t2); System.out.println(DateUtil.isWithinDateTimePeriod(t1, t2, tt)); } }