This article is mainly divided into two parts for date processing. Here is a detailed introduction to it.
Part 1: Basics of date processing
Date class <br />Function: The main function is to obtain the current time and convert the date into a standard format
Date date = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String str = sdf.format(date);System.out.println("2015-10-16 14:59:52"); Convert String to Date type
String day = "2014-6-5 10:30:30";SimpleDateFormat d2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date date2 = d2.parse(day);System.out.println("Thu Jun 05 10:30:30 CST 2014"); Calendar class application
The java.util.Calendar class is an abstract class. You can get a Calendar object by calling the getInstance() static method. This object has been initialized by the current date and time, that is, it represents the current time by default.
Calendar c = Calendar.getInstance();int year = c.get(Calender.YEAR);int month= c.get(Calender.MONTH)+1; //Get the month, 0 means January int day = c.get(Calender.DAY_OF_MONTH);int hour= c.get(Calender.HOUR_OF_DAY);int minute= c.get(Calender.MINUTE);int second = c.get(Calender.SECOND);
Compare the 2 months with different time
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");DateTime d1 = new DateTime(format.parse("2016-10-31 00:00:00"));DateTime d2 = new DateTime(format.parse("2015-1-31 00:00:00"));System.out.println(Math.abs(Months.monthsBetween(d1,d2).getMonths()));Part 2: Date processing tool class
package com.analysys.website.control; import java.text.ParseException;import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar; import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger; /** * Date processing tool class* @author dylan_xu * @date Mar 11, 2012 * @modified by * @modified date * @since JDK1.6 * @see com.util.DateUtil */ public class DateUtil { // ~ Static fields/initializers // ============================================= private static Logger logger = Logger.getLogger(DateUtil.class); private static String defaultDatePattern = null; private static String timePattern = "HH:mm"; private static Calendar cale = Calendar.getInstance(); public static final String TS_FORMAT = DateUtil.getDatePattern() + " HH:mm:ss.S"; /** Date format yyyy-MM string constant*/ private static final String MONTH_FORMAT = "yyyy-MM"; /** Date format yyyy-MM-dd string constant*/ private static final String DATE_FORMAT = "yyyy-MM-dd"; /** Date format HH:mm:ss string constant*/ private static final String HOUR_FORMAT = "HH:mm:ss"; /** Date format yyyy-MM-dd HH:mm:ss string constant*/ private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** Start of a day, minute and second string constant 00:00:00 */ private static final String DAY_BEGIN_STRING_HHMMSS = "00:00:00"; /** Start of a day, minute and second string constant 23:59:59 */ public static final String DAY_END_STRING_HHMMSS = " 23:59:59"; private static SimpleDateFormat sdf_date_format = new SimpleDateFormat(DATE_FORMAT); private static SimpleDateFormat sdf_hour_format = new SimpleDateFormat(HOUR_FORMAT); private static SimpleDateFormat sdf_datetime_format = new SimpleDateFormat(DATETIME_FORMAT); // ~ Methods // ==================================================================================================== public DateUtil() { } /** * Get the current date and time of the server, return in the form of a date string with the format: yyyy-MM-dd HH:mm:ss* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getDateTime() { try { return sdf_datetime_format.format(cale.getTime()); } catch (Exception e) { logger.debug("DateUtil.getDateTime():" + e.getMessage()); return ""; } } /** * Get the current date of the server, return in the form of a date string with the format: yyyy-MM-dd * @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getDate() { try { return sdf_date_format.format(cale.getTime()); } catch (Exception e) { logger.debug("DateUtil.getDate():" + e.getMessage()); return ""; } } /** * Get the current time of the server, return in the form of a date string with the format: HH:mm:ss* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getTime() { String temp = " "; try { temp += sdf_hour_format.format(cale.getTime()); return temp; } catch (Exception e) { logger.debug("DateUtil.getTime():" + e.getMessage()); return ""; } } /** * Default value of the start date during statistics* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getStartDate() { try { return getYear() + "-01-01"; } catch (Exception e) { logger.debug("DateUtil.getStartDate():" + e.getMessage()); return ""; } } /** * Default value of the end date during statistics* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getEndDate() { try { return getDate(); } catch (Exception e) { logger.debug("DateUtil.getEndDate():" + e.getMessage()); return ""; } } /** * Get the year of the current date of the server* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getYear() { try { return String.valueOf(cale.get(Calendar.YEAR)); } catch (Exception e) { logger.debug("DateUtil.getYear():" + e.getMessage()); return ""; } } /** * Get the month of the current date of the server* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getMonth() { try { java.text.DecimalFormat df = new java.text.DecimalFormat(); df.applyPattern("00;00"); return df.format((cale.get(Calendar.MONTH) + 1)); } catch (Exception e) { logger.debug("DateUtil.getMonth():" + e.getMessage()); return ""; } } /** * Get the number of days in the current month of the server* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getDay() { try { return String.valueOf(cale.get(Calendar.DAY_OF_MONTH)); } catch (Exception e) { logger.debug("DateUtil.getDay():" + e.getMessage()); return ""; } } /** * Comparison of the number of days between two dates* @author dylan_xu * @date Mar 11, 2012 * @param date1 * @param date2 * @return */ public static int getMargin(String date1, String date2) { int margin; try { ParsePosition pos = new ParsePosition(0); ParsePosition pos1 = new ParsePosition(0); Date dt1 = sdf_date_format.parse(date1, pos); Date dt2 = sdf_date_format.parse(date2, pos1); long l = dt1.getTime() - dt2.getTime(); margin = (int) (l / (24 * 60 * 60 * 1000)); return margin; } catch (Exception e) { logger.debug("DateUtil.getMargin():" + e.toString()); return 0; } } /** * Comparison of the number of days when the two dates differ* @author dylan_xu * @date Mar 11, 2012 * @param date1 * @param date2 * @return */ public static double getDoubleMargin(String date1, String date2) { double margin; try { ParsePosition pos = new ParsePosition(0); ParsePosition pos1 = new ParsePosition(0); Date dt1 = sdf_datetime_format.parse(date1, pos); Date dt2 = sdf_datetime_format.parse(date2, pos1); long l = dt1.getTime() - dt2.getTime(); margin = (l / (24 * 60 * 60 * 1000.00)); return margin; } catch (Exception e) { logger.debug("DateUtil.getMargin():" + e.toString()); return 0; } } /** * Comparison of the number of months between the two dates* @author dylan_xu * @date Mar 11, 2012 * @param date1 * @param date2 * @return */ public static int getMonthMargin(String date1, String date2) { int margin; try { margin = (Integer.parseInt(date2.substring(0, 4)) - Integer.parseInt(date1.substring(0, 4))) * 12; margin += (Integer.parseInt(date2.substring(4, 7).replaceAll("-0", "-")) - Integer.parseInt(date1.substring(4, 7).replaceAll("-0", "-"))); return margin; } catch (Exception e) { logger.debug("DateUtil.getMargin():" + e.toString()); return 0; } } /** * Return the date after X days of date* @author dylan_xu * @date Mar 11, 2012 * @param date * @param i * @return */ public static String addDay(String date, int i) { try { GregorianCalendar gCal = new GregorianCalendar( Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date.substring(5, 7)) - 1, Integer.parseInt(date.substring(8, 10))); gCal.add(GregorianCalendar.DATE, i); return sdf_date_format.format(gCal.getTime()); } catch (Exception e) { logger.debug("DateUtil.addDay():" + e.toString()); return getDate(); } } /** * Return the date after the date plus X months* @author dylan_xu * @date Mar 11, 2012 * @param date * @param i * @return */ public static String addMonth(String date, int i) { try { GregorianCalendar gCal = new GregorianCalendar( Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date.substring(5, 7)) - 1, Integer.parseInt(date.substring(8, 10))); gCal.add(GregorianCalendar.MONTH, i); return sdf_date_format.format(gCal.getTime()); } catch (Exception e) { logger.debug("DateUtil.addMonth():" + e.toString()); return getDate(); } } /** * Return the date after the date plus X years* @author dylan_xu * @date Mar 11, 2012 * @param date * @param i * @return */ public static String addYear(String date, int i) { try { GregorianCalendar gCal = new GregorianCalendar( Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date.substring(5, 7)) - 1, Integer.parseInt(date.substring(8, 10))); gCal.add(GregorianCalendar.YEAR, i); return sdf_date_format.format(gCal.getTime()); } catch (Exception e) { logger.debug("DateUtil.addYear():" + e.toString()); return ""; } } /** * Return the maximum day of a certain month in a certain year* @author dylan_xu * @date Mar 11, 2012 * @param year * @param month * @return */ public static int getMaxDay(int iyear, int image) { int day = 0; try { if (imonth == 1 || image == 3 || image == 5 || image == 7 || image == 8 || image == 10 || image == 12) { day = 31; } else if (imonth == 4 || image == 6 || image == 9 || image == 11) { day = 30; } else if ((0 == (iyear % 4)) && (0 != (iyear % 100)) || (0 == (iyear % 400))) { day = 29; } else { day = 28; } return day; } catch (Exception e) { logger.debug("DateUtil.getMonthDay():" + e.toString()); return 1; } } /** * Format date* @author dylan_xu * @date Mar 11, 2012 * @param orgDate * @param Type * @param Span * @return */ @SuppressWarnings("static-access") public String rollDate(String orgDate, int Type, int Span) { try { String temp = ""; int iyear, image, iday; int iPos = 0; char seperater = '-'; if (orgDate == null || orgDate.length() < 6) { return ""; } iPos = orgDate.indexOf(seperater); if (iPos > 0) { iyear = Integer.parseInt(orgDate.substring(0, iPos)); temp = orgDate.substring(iPos + 1); } else { iyear = Integer.parseInt(orgDate.substring(0, 4)); temp = orgDate.substring(4); } iPos = temp.indexOf(seperater); if (iPos > 0) { image = Integer.parseInt(temp.substring(0, iPos)); temp = temp.substring(iPos + 1); } else { iPos = temp.indexOf(seperater); if (iPos > 0) { image = Integer.parseInt(temp.substring(0, iPos)); temp = temp.substring(iPos + 1); } else { image = Integer.parseInt(temp.substring(0, 2)); temp = temp.substring(2); } image--; if (imonth < 0 || image > 11) { image = 0; } iday = Integer.parseInt(temp); if (day < 1 || iday > 31) iday = 1; Calendar orgcale = Calendar.getInstance(); orgcale.set(iyear, image, iday); temp = this.rollDate(orgcale, Type, Span); return temp; } catch (Exception e) { return ""; } } public static String rollDate(Calendar cal, int Type, int Span) { try { String temp = ""; Calendar rolcale; rolcale = cal; rolcale.add(Type, Span); temp = sdf_date_format.format(rolcale.getTime()); return temp; } catch (Exception e) { return ""; } } /** * Return the default date format* @author dylan_xu * @date Mar 11, 2012 * @return */ public static synchronized String getDatePattern() { defaultDatePattern = "yyyy-MM-dd"; return defaultDatePattern; } /** * Substitute the specified date into a string in the default format and output, such as: yyyy-MM-dd * @author dylan_xu * @date Mar 11, 2012 * @param aDate * @return */ public static final String getDate(Date aDate) { SimpleDateFormat df = null; String returnValue = ""; if (aDate != null) { df = new SimpleDateFormat(getDatePattern()); returnValue = df.format(aDate); } return (returnValue); } /** * Get the time string for the given date, the format is the current default time format* @author dylan_xu * @date Mar 11, 2012 * @param theTime * @return */ public static String getTimeNow(Date theTime) { return getDateTime(timePattern, theTime); } /** * Get the Calendar calendar object for the current time* @author dylan_xu * @date Mar 11, 2012 * @return * @throws ParseException */ public Calendar getToday() throws ParseException { Date today = new Date(); SimpleDateFormat df = new SimpleDateFormat(getDatePattern()); String todayAsString = df.format(today); Calendar cal = new GregorianCalendar(); cal.setTime(convertStringToDate(todayAsString)); return cal; } /** * Convert the date class to a string form in the specified format* @author dylan_xu * @date Mar 11, 2012 * @param aMask * @param aDate * @return */ public static final String getDateTime(String aMask, Date aDate) { SimpleDateFormat df = null; String returnValue = ""; if (aDate == null) { logger.error("aDate is null!"); } else { df = new SimpleDateFormat(aMask); returnValue = df.format(aDate); } return (returnValue); } /** * Convert the specified date to the string form in the default format* @author dylan_xu * @date Mar 11, 2012 * @param aDate * @return */ public static final String convertDateToString(Date aDate) { return getDateTime(getDatePattern(), aDate); } /** * Convert the date string to the date type in the specified format* @author dylan_xu * @date Mar 11, 2012 * @param aMask The specified date format, such as:yyyy-MM-dd * @param strDate The date string to be converted* @return * @throws ParseException */ public static final Date convertStringToDate(String aMask, String strDate) throws ParseException { SimpleDateFormat df = null; Date date = null; df = new SimpleDateFormat(aMask); if (logger.isDebugEnabled()) { logger.debug("converting '" + strDate + "' to date with mask '" + aMask + "'"); } try { date = df.parse(strDate); } catch (ParseException pe) { logger.error("ParseException: " + pe); throw pe; } return (date); } /** * Convert date string to date type in the default format* @author dylan_xu * @date Mar 11, 2012 * @param strDate * @return * @throws ParseException */ public static Date convertStringToDate(String strDate) throws ParseException { Date aDate = null; try { if (logger.isDebugEnabled()) { logger.debug("converting date with pattern: " + getDatePattern()); } aDate = convertStringToDate(getDatePattern(), strDate); } catch (ParseException pe) { logger.error("Could not convert '" + strDate + "' to a date, throwing exception"); throw new ParseException(pe.getMessage(), pe.getErrorOffset()); } return aDate; } /** * Return a date string of JAVA simple type* @author dylan_xu * @date Mar 11, 2012 * @return */ public static String getSimpleDateFormat() { SimpleDateFormat formatter = new SimpleDateFormat(); String NDateTime = formatter.format(new Date()); return NDateTime; } /** * Comparison of the date in the specified string format with the current time* @author DYLAN * @date Feb 17, 2012 * @param strDate The time required to compare* @return * <p> * int code * <ul> * <li>-1 Current time<Compare time</li> * <li> 0 Current time=Compare time</li> * <li>>=1Current time> Compare time</li> * </ul> * </p> */ public static int compareToCurTime (String strDate) { if (StringUtils.isBlank(strDate)) { return -1; } Date curTime = cale.getTime(); String strCurTime = null; try { strCurTime = sdf_datetime_format.format(curTime); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("[Could not format '" + strDate + "' to a date, throwing exception:" + e.getLocalizedMessage() + "]"); } } if (StringUtils.isNotBlank(strCurTime)) { return strCurTime.compareTo(strDate); } return -1; } /** * Add minimum time to the query date* * @param Target type Date * @param Conversion parameter Date * @return */ @SuppressWarnings("deprecation") public static Date addStartTime(Date param) { Date date = param; try { date.setHours(0); date.setMinutes(0); date.setSeconds(0); return date; } catch (Exception ex) { return date; } } /** * Add maximum time to query date* * @param Target type Date * @param Conversion parameter Date * @return */ @SuppressWarnings("deprecation") public static Date addEndTime(Date param) { Date date = param; try { date.setHours(23); date.setMinutes(59); date.setSeconds(0); return date; } catch (Exception ex) { return date; } } /** * Return the number of days in the system's current year* * @param Month * @return Total days in the specified month*/ @SuppressWarnings("deprecation") public static String getMonthLastDay(int month) { Date date = new Date(); int[][] day = { { 0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 0, 31, 29, 31, 30, 31, 30, 31, 30, 31, 30, 31 } }; int year = date.getYear() + 1900; if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { return day[1][month] + ""; } else { return day[0][month] + ""; } } /** * Return the number of days in the specified month in the specified year* * @param Year year * @param Month month * @return Total days in the specified month*/ public static String getMonthLastDay(int year, int month) { int[][] day = { { 0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31 } }; if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { return day[1][month] + ""; } else { return day[0][month] + ""; } } /** * Judge whether it is a normal year or a leap year* @author dylan_xu * @date Mar 11, 2012 * @param year * @return */ public static boolean isLeapyear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400) == 0) { return true; } else { return false; } } /** * Get the day stamp of the current time* @author dylan_xu * @date Mar 11, 2012 * @return */ @SuppressWarnings("deprecation") public static String getTimestamp() { Date date = cale.getTime(); String timestamp = "" + (date.getYear() + 1900) + date.getMonth() + date.getDate() + date.getMinutes() + date.getSeconds() + date.getTime(); return timestamp; } /** * Get the day stamp of the specified time* * @return */ @SuppressWarnings("deprecation") public static String getTimestamp(Date date) { String timestamp = "" + (date.getYear()) + 1900) + date.getMonth() + date.getDate() + date.getMinutes() + date.getSeconds() + date.getTime(); return timestamp; } public static void main(String[] args) { System.out.println(getYear() + "|" + getMonth() + "|" + getDate()); } }The above is all about this article, I hope it will be helpful to everyone's learning.