Java Date Tool class

Source: Internet
Author: User

public class dateutil{//default display date format public static final String dataformat_str = "YYYY-MM-DD";         Format of the default display date public static final String yyyy_mm_dataformat_str = "yyyy-mm";         Default display datetime format public static final String datatimef_str = "Yyyy-mm-dd HH:mm:ss";         The format of the Simplified Chinese date is displayed by default public static final String zhcn_dataformat_str = "yyyy mm month dd Day";         Default display of Simplified Chinese date time format public static final String zhcn_datatimef_str = "yyyy mm month DD day hh" mm min SS second ";         Default display of Simplified Chinese date time format public static final String zhcn_datatimef_str_4ymmddhhmm = "yyyy mm month DD day hh mm";         private static DateFormat DateFormat = null;         private static DateFormat DateTimeFormat = null;         private static DateFormat Zhcndateformat = null;    private static DateFormat Zhcndatetimeformat = null;        static {DateFormat = new SimpleDateFormat (DATAFORMAT_STR);        DateTimeFormat = new SimpleDateFormat (DATATIMEF_STR); Zhcndateformat = new SimpleDateFormat (zhcn_dataformat_STR);    Zhcndatetimeformat = new SimpleDateFormat (ZHCN_DATATIMEF_STR); } private static DateFormat GetDateFormat (String formatstr) {if (Formatstr.equalsignorecase (dataformat_        STR) {return dateformat;             } else if (Formatstr.equalsignorecase (DATATIMEF_STR)) {return datetimeformat;                    } else if (Formatstr.equalsignorecase (ZHCN_DATAFORMAT_STR)) {                return zhcndateformat;                        } else if (Formatstr.equalsignorecase (ZHCN_DATATIMEF_STR)) {                    return zhcndatetimeformat;                    } else {return new SimpleDateFormat (FORMATSTR); }}/** * According to the default display date time format "Yyyy-mm-dd HH:mm:ss", conversion datetimestr to date type * Datetimestr must be "Yyyy-mm-dd H H:mm:ss "Form * @param daTETIMESTR * @return */public static Date getDate (String datetimestr) {return getDate (DATETIMESTR, D    ATATIMEF_STR); }/** * According to the default formatstr format, conversion datetimestr to date type * DATETIMESTR must be in the form of FORMATSTR * @param datetimestr *        @param formatstr * @return */public static Date getDate (String datetimestr, String formatstr) {try            {if (Datetimestr = = NULL | | datetimestr.equals ("")) {return null;            } dateformat sdf = GetDateFormat (FORMATSTR);            Java.util.Date d = sdf.parse (DATETIMESTR);        return D;        } catch (ParseException e) {throw new RuntimeException (e); }}/** * Converts YYYYMMDD to a date date * @param date * @return * @throws businessexception */Publ            IC Static date transferdate (String date) throws Exception {if (Date = = NULL | | date.length () < 1)      return null;           if (Date.length ()! = 8) throw new Exception ("date format error");                 String con = "-";        String yyyy = date.substring (0, 4);        String mm = date.substring (4, 6);                 String dd = date.substring (6, 8);        int month = Integer.parseint (mm);        int day = Integer.parseint (DD);                 if (Month < 1 | | month > | | Day < 1 | | days > To) throw new Exception ("date format error");        String str = yyyy + con + mm + con + dd;    return Dateutil.getdate (str, DATEUTIL.DATAFORMAT_STR); /** * Convert yyyy-mm-dd date to YYYYMMDD format string * @param date * @return */public static string Getyyyymm        Dddate (date date) {if (date = = null) return null;        String yyyy = getYear (date) + "";        String mm = GetMonth (date) + "";                 String dd = GetDay (date) + "";        MM = Stringutil.rightalign (mm, 2, "0");        DD = Stringutil.rightalign (DD, 2, "0"); return yyyy + mm+ DD; /** * Convert yyyy-mm-dd date to YYYYMMDDHHMMSS format string * @param date * @return */public static string get        Yyyymmddhhmmssdate (date date) {if (date = = null) return null;        String yyyy = getYear (date) + "";        String mm = GetMonth (date) + "";        String dd = GetDay (date) + "";        String hh = gethour (date) + "";        String min = getmin (date) + "";                 String SS = Getsecond (date) + "";        MM = Stringutil.rightalign (mm, 2, "0");        DD = Stringutil.rightalign (DD, 2, "0");        HH = Stringutil.rightalign (hh, 2, "0");        min = stringutil.rightalign (min, 2, "0");                 SS = Stringutil.rightalign (ss, 2, "0");    return yyyy + mm + dd + hh + min + ss; /** * Convert yyyy-mm-dd date to YYYYMMDD format string * @param date * @return */public static string Getyyyymm    Dddate (String date) {return getyyyymmdddate (getDate (date, dataformat_str)); }/** * Convert date to String"Yyyy-mm-dd hh:mm:ss" String * @param date * @return */public static string datetodatestring (date date) {    return datetodatestring (date, datatimef_str);  /** * Convert date to FORMATSTR format string * @param date * @param formatstr * @return */public static        String datetodatestring (date date, String formatstr) {DateFormat df = GetDateFormat (FORMATSTR);    return Df.format (date); }/** * Returns a YYYY-MM-DD HH:mm:ss in a datetime string in the form of HH:MM:SS * @param dateTime * @return */public stat    IC string gettimestring (string datetime) {return gettimestring (datetime, DATATIMEF_STR);    }/** * Returns the HH:MM:SS * @param datetime * @param formatstr * @return * * In a datetime string of formatstr format * *        public static string Gettimestring (String dateTime, String formatstr) {Date d = getDate (datetime, FORMATSTR);        String s = datetodatestring (d); Return s.substring (Datatimef_str.indexof (' H‘)); }/** * Gets the form of the current date YYYY-MM-DD * @return */public static String Getcurdate () {//return dat        Etodatestring (New Date (), DATAFORMAT_STR);    Return datetodatestring (Calendar.getinstance (). GetTime (), DATAFORMAT_STR); /** * Gets the current date yyyy mm month dd Day form * @return */public static String Getcurzhcndate () {return    Datetodatestring (New Date (), ZHCN_DATAFORMAT_STR);        }/** * Gets the form of the current datetime yyyy-mm-dd HH:MM:SS * @return */public static String Getcurdatetime () {    Return datetodatestring (New Date (), DATATIMEF_STR);         }/** * Gets the current datetime yyyy mm month DD Day hh the form of mm minutes ss seconds * @return */public static String Getcurzhcndatetime () {    Return datetodatestring (New Date (), ZHCN_DATATIMEF_STR); }/** * Gets a date for days after day of D @param d * @param-@return * */public static date GetInt Ernaldatebyday (Date D, int days) {Calendar now = Calendar.getinsTance (Timezone.getdefault ());        Now.settime (d);        Now.add (Calendar.date, days);    return Now.gettime (); } public static Date Getinternaldatebymon (date d, int months) {Calendar now = calendar.getinstance (time        Zone.getdefault ());        Now.settime (d);        Now.add (calendar.month, months);    return Now.gettime (); } public static Date getinternaldatebyyear (Date d, int years) {Calendar now = calendar.getinstance (time        Zone.getdefault ());        Now.settime (d);        Now.add (Calendar.year, years);    return Now.gettime (); The public static date getinternaldatebysec (Date D, int. sec) {Calendar now = calendar.getinstance (Timezon        E.getdefault ());        Now.settime (d);        Now.add (Calendar.second, SEC);    return Now.gettime (); public static date Getinternaldatebymin (Date D, Int. min) {Calendar now = calendar.getinstance (Timezon        E.getdefault ());        Now.settime (d); Now.aDD (Calendar.minute, Min);    return Now.gettime (); } public static Date Getinternaldatebyhour (date d, int hours) {Calendar now = calendar.getinstance (time        Zone.getdefault ());        Now.settime (d);        Now.add (Calendar.hour_of_day, hours);    return Now.gettime (); }/** * Returns a date format based on a date string, currently supports 4 types * If none, then returns NULL * @param datestring * @return */Public STA Tic String Getformatestr (String datestring) {string patternStr1 = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}";//"yyyy-mm- DD "String patternStr2 =" [0-9]{4}-[0-9]{1,2}-[0-9]{1,2}\\s[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} ";        "Yyyy-mm-dd HH:mm:ss"; String PATTERNSTR3 = "[0-9]{4} Year [0-9]{1,2} month [0-9]{1,2} day";//"YYYY year mm DD Day" string PATTERNSTR4 = "[0-9]{4} Year [0-9]{1,2} month [0] -9]{1,2} Day [0-9]{1,2} [0-9]{1,2} minutes [0-9]{1,2} seconds ',//' YYYY year mm month DD Day hh ' mm min ss sec ' Pattern p = pattern.compile (patternst        R1);        Matcher m = P.matcher (datestring); Boolean B = m.matches ();       if (b) return dataformat_str;        p = pattern.compile (PATTERNSTR2);        m = P.matcher (datestring);        b = m.matches ();                 if (b) return datatimef_str;        p = pattern.compile (PATTERNSTR3);        m = P.matcher (datestring);        b = m.matches ();                 if (b) return zhcn_dataformat_str;        p = pattern.compile (PATTERNSTR4);        m = P.matcher (datestring);        b = m.matches ();        if (b) return zhcn_datatimef_str;    return null;    }/** * Converts a "yyyy-mm-dd HH:mm:ss" string into a string of "mm min SS S" for yyyy year MM DD Day HH * @param datestr * @return * *        public static string Getzhcndatetime (String datestr) {Date d = getDate (DATESTR);    Return datetodatestring (d, ZHCN_DATATIMEF_STR); }/** * Converts a "yyyy-mm-dd" string to "yyyy MM DD Day" String * @param datestr * @return */public static STR ing getzhcndate (String datestr) {Date d = getDate (datestR, Dataformat_str);    Return datetodatestring (d, ZHCN_DATAFORMAT_STR);      }/** * Convert Datestr from Fmtfrom to fmtto format * @param datestr * @param fmtfrom * @param fmtto * @return */public static string Getdatestr (String datestr, String fmtfrom, String fmtto) {Date d = getDate (date        STR, Fmtfrom);    Return datetodatestring (d, Fmtto); }/** * Compares the dates in two "Yyyy-mm-dd HH:mm:ss" formats, the number of milliseconds between time2-time1 * @param time1 * @param time2 * @retur        n */public static long Comparedatestr (string time1, String time2) {Date D1 = getDate (time1);        Date D2 = GetDate (time2);    Return D2.gettime ()-d1.gettime (); /** * Convert hours to return time in milliseconds * @param hours * @return * */public static long Getmicrosec (Bigdecima        L hours) {BigDecimal BD;        BD = hours.multiply (New BigDecimal (3600 * 1000));    return Bd.longvalue (); /** * Gets the minutes in date * @param d * @retURN */public static int getmin (Date d) {Calendar now = Calendar.getinstance (Timezone.getdefault ());        Now.settime (d);    Return Now.get (Calendar.minute);        /** * Gets the hour in Date (24 hours) * @param d * @return */public static int Gethour (Date d) {        Calendar now = Calendar.getinstance (Timezone.getdefault ());        Now.settime (d);    Return Now.get (Calendar.hour_of_day); /** * Gets the seconds in Date * @param d * @return */public static int Getsecond (Date d) {Calen        Dar now = calendar.getinstance (Timezone.getdefault ());        Now.settime (d);    Return Now.get (Calendar.second); }/** * gets xxxx-xx-xx day * @param d * @return */public static int GetDay (Date d) {Cal        Endar now = Calendar.getinstance (Timezone.getdefault ());        Now.settime (d);    Return Now.get (Calendar.day_of_month);  }/** * Get month, January-December * @param d * @return * *  public static int GetMonth (Date d) {Calendar now = Calendar.getinstance (Timezone.getdefault ());        Now.settime (d);    Return Now.get (Calendar.month) + 1; }/** * Gets the year of 19xx,20xx form * @param d * @return */public static int getYear (Date d) {C        Alendar now = Calendar.getinstance (Timezone.getdefault ());        Now.settime (d);    Return Now.get (calendar.year);        }/** * gets d for the year + month of the previous month, such as 200505 * @return */public static String Getyearmonthoflastmon (Date d) {        Date newdate = Getinternaldatebymon (d,-1);        String year = string.valueof (GetYear (newdate));        String month = string.valueof (GetMonth (newdate));    Return year + month; }/** * Gets the current date of the year and month as 200509 * @return String */public static string Getcuryearmonth () {Ca        Lendar now = Calendar.getinstance (Timezone.getdefault ());        String date_format = "Yyyymm"; Java.text.SimpleDateFormat SDF = new Java.text.SimpleDateFormat (Date_format);        Sdf.settimezone (Timezone.getdefault ());    Return (Sdf.format (Now.gettime ())); public static Date Getnextmonth (string year, string month) {string datestr = year + "-" + month + "-0        1 ";        Date date = GetDate (Datestr, DATAFORMAT_STR);    return Getinternaldatebymon (date, 1); public static Date Getlastmonth (string year, string month) {string datestr = year + "-" + month + "-0        1 ";        Date date = GetDate (Datestr, DATAFORMAT_STR);    return Getinternaldatebymon (date,-1); /** * Gets the date D, according to the page date control format, such as "2001-3-16" * @param d * @return */public static String Getsinglenum    Date (Date D) {return datetodatestring (d, DATAFORMAT_STR); /** * Get D six months ago date, "Yyyy-mm-dd" * @param d * @return */public static String Gethalfyearbeforest   R (Date d) {return datetodatestring (Getinternaldatebymon (d,-6), DATAFORMAT_STR); /** * Gets the current date D at the end of the month before/after several days of the time, <0 said before, >0 said after * @param d * @param days * @return */Pub Lic static String Getinternaldatebylastday (Date d, int days) {return datetodatestring (getinternaldateb    Yday (d, Days), DATAFORMAT_STR);     }/** * Date added * @param field int need to add fields month Day * @param amount int plus how much * @return String        */public static String adddate (int field, int amount) {int temp = 0;        if (field = = 1) {temp = Calendar.year;        } if (field = = 2) {temp = Calendar.month;        } if (field = = 3) {temp = Calendar.date;        } String time = "";            try {simpledateformat SDF = new SimpleDateFormat ("Yyyy-mm-dd");            Calendar cal = Calendar.getinstance (Timezone.getdefault ());            Cal.add (temp, amount);            Time = Sdf.format (Cal.gettime ()); Returntime;            } catch (Exception e) {e.printstacktrace ();        return null; }}/** * Gets the number of days of the system's current month * @return */public static int Getcurentmonthday () {Da        Te date = Calendar.getinstance (). GetTime ();    return Getmonthday (date); /** * Gets the number of days of the specified date month * @return */public static int Getmonthday (date date) {Calendar c =        Calendar.getinstance ();        C.settime (date);             Return C.getactualmaximum (Calendar.day_of_month);        /** * Gets the number of days of the specified date month YYYY-MM-DD * @return */public static int Getmonthday (String date) {        Date strdate = getDate (date, dataformat_str);             Return Getmonthday (strdate); } public static String getstringdate (Calendar cal) {SimpleDateFormat format = new Simpledatefo        Rmat ("Yyyy-mm-dd");    Return Format.format (Cal.gettime ()); }/** * @param args * *   public static void Main (string[] args) {////system.out.print (Dateutil.getdate ("04:04:04", "HH:mm:ss"));        System.out.print ("\ n" +dateutil.getcurzhcndatetime ());        System.out.print ("\ n" +getformatestr (Dateutil.getcurdate ()));        System.out.print ("\ n" +comparedatestr ("1900-1-1 1:1:2", "1900-1-1 1:1:3"));        System.out.print ("\ n" +getday (new Date ()));        System.out.print ("\ n" +getmonth (new Date ()));        System.out.print ("\ n" +getyear (new Date ()));        System.out.print ("\ n" +getmin (new Date ()));        System.out.print ("\ n" +new Date (). getseconds ());        /*date D1 = new Date (2007,11,30);        Date D2 = new Date (2007,12,1);        if (D2.compareto (D1) >0) {System.out.println ("D2 greater than D1");        }else{System.out.println ("D2 less than D1");        }*/System.out.println (Adddate (1, 1));        System.out.println (Adddate (2, 1)); System.out.println (Adddate (3, 1));                 System.out.println (Getyyyymmddhhmmssdate (New Date ()));             System.out.println (Getcurentmonthday ()); }     }

  

Java Date Tool class

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.