Java Date Manipulation Tool class

Source: Internet
Author: User
Tags date1 string format

Original: Java Date manipulation Tool class

Source code: Http://www.zuidaima.com/share/1550463481580544.htm

Here are some of the commonly used date processing methods, written is very comprehensive, I hope someone can write their own good date processing code updated into the inside

Package Com.zuidaima.date.util;import Java.text.parseposition;import Java.text.simpledateformat;import Java.util.calendar;import Java.util.date;import Java.util.regex.pattern;import Org.apache.commons.logging.Log; Import org.apache.commons.logging.logfactory;/*** @author Www.zuidaima.com**/public class Dateutil {protected static Log logger = Logfactory.getlog (dateutil.class);//format: Year-month-day hour: minutes: Second public static final String Format_one = "Yyyy-mm-dd    HH:mm:ss ";    Format: Year-month-day hour: minutes public static final String format_two = "Yyyy-mm-dd hh:mm";    Format: Month Day hour minute second public static final String Format_three = "YYYYMMDD-HHMMSS";    Format: Year-month-day public static final String Long_date_format = "YYYY-MM-DD";    Format: Month-day public static final String Short_date_format = "MM-DD";    Format: Hours: minutes: Seconds public static final String Long_time_format = "HH:mm:ss";    Format: Year-month public static final String Montg_date_format = "yyyy-mm";    The plus and minus public static final int sub_year = calendar.year; //Month plus minus public static final int sub_month = Calendar.month;    Days of addition and subtraction public static final int sub_day = calendar.date;    Hours of addition and subtraction public static final int sub_hour = Calendar.hour;    Addition and subtraction of minutes public static final int sub_minute = Calendar.minute;    The addition and subtraction of the second public static final int sub_second = Calendar.second;    Static final String daynames[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; @SuppressWarnings ("unused") private static final SimpleDateFormat TimeFormat = new SimpleDateFormat ("Yyyy-m    M-dd HH:mm:ss "); Public Dateutil () {}/** * Converts a string that conforms to a date format to a date type */public static date Stringtodate (string datestr, String        Format) {Date d = null;        SimpleDateFormat formater = new SimpleDateFormat (format);            try {formater.setlenient (false);        D = Formater.parse (DATESTR);        } catch (Exception e) {d = null;    } return D; /** * Converts a string that matches a date format to a date type * @author www.zuidaima.com */public static java.util.Date stringtodate (string datestr, string format, Pa        Rseposition POS) {Date d = null;        SimpleDateFormat formater = new SimpleDateFormat (format);            try {formater.setlenient (false);        D = Formater.parse (Datestr, POS);        } catch (Exception e) {d = null;    } return D; }/** * Convert date to String */public static string datetostring (java.util.Date date, string format) {string R        Esult = "";        SimpleDateFormat formater = new SimpleDateFormat (format);        try {result = Formater.format (date);        } catch (Exception e) {//Log.error (e);    } return result; /** * Gets the specified format of the current time */public static string Getcurrdate (string format) {return datetostring (new date    (), format); public static string datesub (int datekind, string datestr, int amount) {Date date = StringtodatE (Datestr, format_one);        Calendar calendar = Calendar.getinstance ();        Calendar.settime (date);        Calendar.add (Datekind, amount);    Return datetostring (Calendar.gettime (), format_one);        }/** * Two date subtraction * @return Subtract the number of seconds */public static long Timesub (string firsttime, String sectime) {        Long first = Stringtodate (Firsttime, Format_one). GetTime ();        Long second = Stringtodate (Sectime, Format_one). GetTime ();    Return (Second-first)/1000;        }/** * Gets the number of days in a month */public static int Getdaysofmonth (string year, string month) {int day = 0;  if (Month.equals ("1") | | | month.equals ("3") | | month.equals ("5") | | month.equals ("7") | | month.equals ("8") || Month.equals ("10") | |        Month.equals ("n")) {days = 31;            } else if (Month.equals ("4") | | | month.equals ("6") | | month.equals ("9") | | month.equals ("11")) {        days = 30; } else {if (Integer.parseint (year)% 4 = = 0 && integer.parseint (year)% 100! = 0) | |            Integer.parseint (year)% + = = 0) {days = 29;            } else {days = 28;    }} return days; /** * Gets the number of days of the month in a year */public static int getdaysofmonth (int year, int month) {Calendar calendar = Cale        Ndar.getinstance ();        Calendar.set (year, month-1, 1);    Return Calendar.getactualmaximum (Calendar.day_of_month);        }/** * Gets the current date */public static int gettoday () {Calendar calendar = calendar.getinstance ();    Return Calendar.get (calendar.date);        }/** * Gets the current month */public static int gettomonth () {Calendar calendar = calendar.getinstance ();    Return Calendar.get (Calendar.month) + 1;        }/** * Gets the current year */public static int gettoyear () {Calendar calendar = calendar.getinstance ();    Return Calendar.get (calendar.year); }    /**     * Day of Return date */public static int GetDay (date date) {Calendar calendar = calendar.getinstance ();        Calendar.settime (date);    Return Calendar.get (calendar.date);        }/** * Returns the year of the date */public static int getYear (date date) {Calendar calendar = calendar.getinstance ();        Calendar.settime (date);    Return Calendar.get (calendar.year); }/** * Returns the month of the date, 1-12 */public static int getMonth (date date) {Calendar calendar = Calendar.getinsta        NCE ();        Calendar.settime (date);    Return Calendar.get (Calendar.month) + 1;        }/** * Calculates the number of days between two dates, if Date2 > date1 returns positive numbers, otherwise returns negative */public static long Daydiff (date date1, date date2) {    Return (Date2.gettime ()-date1.gettime ())/86400000; }/** * Compares the year difference of two dates */public static int Yeardiff (string before, string after) {Date Beforeday = Strin        Gtodate (before, Long_date_format); Date Afterday = Stringtodate (After, long_date_format);    Return GetYear (Afterday)-getYear (Beforeday);        /** * Compare the difference between the specified date and the current date */public static int Yeardiffcurr (String after) {Date beforeday = new Date ();        Date Afterday = Stringtodate (after, Long_date_format);    Return GetYear (Beforeday)-getYear (Afterday); /** * Compare the difference between the specified date and the current date */public static long Daydiffcurr (String before) {Date currdate = Dateutil        . Stringtodate (Currday (), Long_date_format);        Date beforedate = Stringtodate (before, Long_date_format);    Return (Currdate.gettime ()-beforedate.gettime ())/86400000; }/** * Gets the current date * */public static String Currday () {return datetostring (new Date (), Long_date_format    ); }/** * Gets the first week of the month */public static int getfirstweekdayofmonth (int year, int month) {Calendar c =        Calendar.getinstance (); C.setfirstdayofweek (Calendar.saturday);        Sunday for the first day C.set (year, month-1, 1); Return C.get (CalendaR.day_of_week); }/** * Gets the last week of the month */public static int getlastweekdayofmonth (int year, int month) {Calendar c = Cale        Ndar.getinstance (); C.setfirstdayofweek (Calendar.saturday);        Sunday for the first day C.set (year, Month-1, Getdaysofmonth (year, month));    Return C.get (Calendar.day_of_week); }/** * Gets the current date string, format "YYYY-MM-DD HH:mm:ss" * * @return */public static string Getnow () {Cal        Endar today = Calendar.getinstance ();    Return datetostring (Today.gettime (), format_one); }/** * Convert java.util.date type to Java.sql.date * @param date * @return */public static Java.sql.Timesta MP GetDate (Java.util.Date Date) {//java.sql.date sqldate = new Java.sql.Date (); Java.sql.Timestamp Timestamp = new JAVA.SQ    L.timestamp (Date.gettime ()); return Timestamp;} /** * Determines whether a date is valid, including a leap year condition * * @param date * YYYY-MM-DD * @return * */public static Boolea n isDate (String date) {StringbuFfer reg = new StringBuffer ("^ ((\\d{2} (([02468][048]) | ( [13579] [26])) -?        ((0? "); Reg.append ("[13578]) | (1[02])) -? ((0? [1-9]) | ([1-2][0-9]) |        (3[01])) "); Reg.append ("| ( ((0? [469]) | (11)) -? ((0? [1-9]) | ([1-2][0-9]) |        (30))) | "); Reg.append ("(0?2-?" ( (0?) [1-9]) | ([1-2][0-9])))) |        (\\d{2} ([02468][12 "); Reg.append ("35679]) | ([13579][01345789])) -? (((0? [13578]) |        (1[02])); Reg.append ("-?" ( (0?) [1-9]) | ([1-2][0-9]) | (3[01])) | ((0? [469]) |        (11)) "); Reg.append ("-?" ( (0?) [1-9]) | ([1-2][0-9]) | (30))) | (0?2-?) ((0?        ["); Reg.append ("1-9]) | (1[0-9]) |        (2[0-8])))));        Pattern p = pattern.compile (reg.tostring ());    return P.matcher (date). matches (); }}

Java Date Manipulation Tool class

Related Article

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.