Java Date processing Tool class _java

Source: Internet
Author: User
Tags date1 getmessage string format gcal

This article aims at the date processing to study uses, mainly divides into two parts, below for everybody specific introduction

The first part: The basics of date processing

Date class
Role: The main function is to obtain the current time
Convert a date to 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");

Converts a string to a 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 June 10:30:30 CST 2014");

The application of the Calendar class

The Java.util.Calendar class is an abstract class that can get a Calendar object by calling the GetInstance () static method, which is initialized by the current date time, which is the default representing the current time

 Calendar C = calendar.getinstance ();
int year = C.get (calender.year);
int month= c.get (calender.month) +1; Gets 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 2 month of time difference

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 II: 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, * @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"; 
  /** one day at the beginning of the minute string constant 00:00:00/private static final String Day_begin_string_hhmmss = "00:00:00"; 
  /** the end of the day, the seconds 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 server's current date and time, in the format of: Yyyy-mm-dd HH:mm:ss Date String form return * @author Dylan_xu * @date * @return * * public staticString GetDateTime () {try {return Sdf_datetime_format.format (Cale.gettime ()); 
      catch (Exception e) {logger.debug ("Dateutil.getdatetime ():" + e.getmessage ()); 
    Return ""; 
   /** * Gets the server's current date in the format of: yyyy-mm-dd date string return * @author Dylan_xu * @date * @return 
    */public static String GetDate () {try {return Sdf_date_format.format (Cale.gettime ()); 
      catch (Exception e) {logger.debug ("dateutil.getdate ():" + e.getmessage ()); 
    Return ""; 
   /** * Gets the server's current time and returns it in the form of a date string of HH:mm:ss * @author Dylan_xu * @date * @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 ""; }}/** * Statistics The default value of the start date * @author Dylan_xu *@date Mar * @return/public static String Getstartdate () {try {return getyear () + "-01 
    -01 "; 
      catch (Exception e) {logger.debug ("dateutil.getstartdate ():" + e.getmessage ()); 
    Return ""; }/** * Statistics The default value of the end date * @author Dylan_xu * @date, * @return/public static S 
    Tring Getenddate () {try {return getDate (); 
      catch (Exception e) {logger.debug ("dateutil.getenddate ():" + e.getmessage ()); 
    Return ""; /** * Get the year of the server's current date * @author Dylan_xu * @date-@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 server's current date * @author Dylan_xu * @date-@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 server days in the current month * @author Dylan_xu * @date (*) @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 ""; 
   }/** * Compare two days of difference * @author Dylan_xu * @date Mar, * @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; 
   }/** * Compare two days of difference * @author Dylan_xu * @date Mar, * @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; }/** * Compares the number of months that differ by two dates 
   * @date @author Dylan_xu * @param date1 * @param date2 * @return * * Public stat 
    IC 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 date plus x Day * @author Dylan_xu * @date Mar, * @param date * @param i * @return */public static string Addday (String date, int i) {try {GregorianCalendar gCal = new Gregori  
          Ancalendar (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 date plus x-month date * @author Dylan_xu * @date Mar, * @param date * @param i * @return */public static string Addmonth (String date, int i) {try {GregorianCalendar gCal = new Grego  
          Riancalendar (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 date plus x year date * @author Dylan_xu * @date Mar, * @param date * @param i * 
 @return  */public static string Addyear (String date, int i) {try {GregorianCalendar gCal = new Gregoriancalenda  
          R (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 ""; 
   }/** * Returns the maximum day of the month of the year * @author Dylan_xu * @date Mar, * @param year * @param month 
    * @return/public static int getmaxday (int iyear, int imonth) {int day = 0; try {if (Imonth = 1 | | imonth = 3 | | imonth = 5 | | imonth = 7 | | imonth = 8 | | imonth = 
      nth = = 31; 
      else if (Imonth = 4 | | imonth = 6 | | | imonth = 9 | | imonth = one) {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 (*) @param orgdate * @param Type *  @param Span * @return/@SuppressWarnings ("static-access") public string Rolldate (string orgdate, int Type, 
      int Span) {try {String temp = '; 
      int iyear, imonth, 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) {imonth = Integer.parseint (temp.substring (0, IPos)); 
      temp = temp.substring (IPos + 1); 
        else {imonth = Integer.parseint (temp.substring (0, 2)); 
      temp = temp.substring (2); 
      } imonth--; 
      if (Imonth < 0 | | | imonth > One) {imonth = 0; 
      } iday = Integer.parseint (temp); 
  
      if (Iday < 1 | | | iday >) iday = 1; 
      Calendar Orgcale = Calendar.getinstance (); 
      Orgcale.set (Iyear, Imonth, iday); 
      temp = This.rolldate (Orgcale, Type, Span); 
    return temp; 
    catch (Exception e) {return ""; 
      The 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 ""; }/** * Returns the default date format * @author Dylan_xu * @date-@return */public static SYN 
    chronized String Getdatepattern () {Defaultdatepattern = "yyyy-mm-dd"; 
  return defaultdatepattern; 
   /** * To format the specified date in the default format into a string and output such as: YYYY-MM-DD * @author dylan_xu * @date * @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); /** * Gets the time string for the given date, in the current default time format * @author Dylan_xu * @date * @param thetime * @ret 
  URN */public static String Gettimenow (Date thetime) {return GetDateTime (Timepattern, thetime); /** * Get the Calendar Calendar object for the current time * @author Dylan_xu * @date Mar * @return * @throws parseexception/public Calendar Gettoday () throws ParseException {Dat 
    E today = new Date (); 
    SimpleDateFormat df = new SimpleDateFormat (Getdatepattern ()); 
    String todayasstring = Df.format (today); 
    Calendar cal = new GregorianCalendar (); 
    Cal.settime (Convertstringtodate (todayasstring)); 
  Return cal; 
   /** * Converts a date class to a string form of the specified format * @author Dylan_xu * @date-@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); 
   /** * Converts the specified date to a string form of the default format * @author Dylan_xu * @date-@param adate * @return * * public static finalString convertdatetostring (Date adate) {return GetDateTime (Getdatepattern (), adate); /** * Converts date strings to date types in the specified format * @author Dylan_xu * @date Mar, * @param amask specified date format, such as: yyyy-mm- DD * @param strdate Date string to be converted * @return * @throws parseexception * * public static final date Convertstr 
    Ingtodate (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); 
   /** * Converts a date string to the date type by default format * @author Dylan_xu * @date-@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;  /** * Returns a Java simple Type date string * @author Dylan_xu * @date-@return/public static 
    String Getsimpledateformat () {SimpleDateFormat formatter = new SimpleDateFormat (); 
    String ndatetime = Formatter.format (New Date ()); 
  return ndatetime; /** * Compares the date specified in the string format with the current time * @author DYLAN * @date Feb, * @param strdate need to compare time * @ret URN * <p> * int code * <ul> * <li>-1 Current time < comparison time </li> * <li> 0 Current time = comparison time </li> * <li>>=1 Current time > comparison time </li> * </ul> * </p>/public static int comparetocurtime (String strdate) {if stringutils.i 
    Sblank (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 +" ' t 
      o A date, throwing exception: "+ e.getlocalizedmessage () +"]); 
    } if (Stringutils.isnotblank (Strcurtime)) {return Strcurtime.compareto (strdate); 
  } return-1; /** * Add minimum time for query date * * @param target Type Date * @param conversion parameter Date * @return * * @SuppressWarning 
    S ("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/@SuppressWarn 
    Ings ("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; }/** * Returns the number of days of the specified month in the current year * * @param month month * @return Total days of the specified month * * * @SuppressWarnings ("Depr 
    Ecation ") 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, 31, 30, 3 
    1, 30, 31}}; 
    int year = Date.getyear () + 1900; if (year% 4 = 0 && Year%!= 0 | | [Year% = = 0) {return day[1][month] + ""; 
    else {return day[0][month] + ""; }/** * Returns the number of days specified in the specified year * * @param years Year * @param month month * @return The total number of days in a specified month * * * publi C Static String getmonthlastday (int month) {int[][] day = {0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 3 
    0, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; 
    if (year% 4 = 0 && Year%!= 0 | |-year% = = 0) {return day[1][month] + ""; 
    else {return day[0][month] + ""; 
  }/** * Judgment is excepting or leap year * @author Dylan_xu * @date-@param year * @return * * public static Boolean isleapyear (int year) {if (year% 4 = 0 && Year% 100!= 0) | | 
    (year%) = = 0) {return true; 
    else {return false; }/** * Postmarks * @author dylan_xu * @date * @return * * @SuppressWarnings ("deprecation") public static STRing Gettimestamp () {Date date = Cale.gettime (); String timestamp = "" + (Date.getyear () + 1900) + date.getmonth () + date.getdate () + date.getminutes () + Date.get 
    Seconds () + date.gettime (); 
  return timestamp; /** * postmarks * * * @return * * * @SuppressWarnings ("deprecation") public static String for the specified time GetTime Stamp (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 the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.