Let's talk about several common operations on dates in Java-value, conversion, addition, subtraction, comparison, and java Value

Source: Internet
Author: User

Let's talk about several common operations on dates in Java-value, conversion, addition, subtraction, comparison, and java Value

During Java development, there is no need to be entangled with the Date type. I am going to summarize the Date-related operations that are frequently used in the project, JDK 1.7. If it can help you save a few minutes and get up for activities, it's great to have a cup of coffee, hey. Of course, I only provide feasible solutions and it is not guaranteed to be the best practice.

1. Date Value

In the old version of JDK, many codes use java for date values. util. date class, but since the Date class is not easy to implement internationalization, java is recommended since JDK1.1. util. the Calendar class processes the time and date. Here we will not introduce the operations of the Date class. Let's go straight to the topic and use the Calendar class to get the current Date and time.

Since the Calendar constructor method is modified by protected, we will use the getInstance method provided in the API to create the Calendar Object.

1 // There are multiple overload methods to create the Calendar Object 2 Calendar now = Calendar. getInstance (); // default value: 3 // specify the time zone and region. You can also enter only one of the parameters. getInstance (timeZone, locale );

Then we can get the current time parameters through this object.

Int year = now. get (Calendar. YEAR); // 2015, current YEAR int month = now. get (Calendar. MONTH) + 1; // 12, the current MONTH, note that the 1int day = now is added. get (Calendar. DATE); // 23, current day
Date date = now. getTime (); // directly obtain a Date of the Date type

To obtain other types of time data, you only need to modify the parameters in now. get (). In addition to the preceding three parameters, other common parameters are as follows:

  • Calendar. DAY_OF_MONTH: DATE, which is the same as Calendar. DATE.
  • Calendar. HOUR: hours in 12-HOUR format
  • Calendar. HOUR_OF_DAY: 24-hour
  • Calendar. MINUTE: MINUTE
  • Calendar. SECOND: seconds
  • Calendar. DAY_OF_WEEK: number of weeks

In addition to obtaining time data, we can also set various time parameters through the Calendar Object.

1 // only set the value of a field 2 // public final void set (int field, int value) 3 now. set (Calendar. YEAR, 2016); 4 // set year month day or YEAR month day hour or year month day hour minute second 5 // public final void set (int YEAR, int month, int date [, int hourOfDay, int minute, int second]) 6 now. set (2016, 1, 1 [, 11, 1, 1]); 7 // directly input a Date type Date 8 // public final void setTime (date Date) 9 now. set (date );

Note:

  • After the time parameter is set, other related values will be recalculated. For example, if you set the date to the 11th day, the corresponding changes will be made in the week.
  • The obtained month plus 1 is the actual month.
  • In the Calendar class, Sunday is 1, Monday is 2, and so on.
2. date conversion

After talking about Date values, let's talk about Date conversion. The conversion is generally the conversion between Date and String types. I mainly use java. text. SimpleDateFormat for conversion.

1 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); 2 try {3 // convert date to string 4 Calendar calendar = Calendar. getInstance (); 5 Date date = calendar. getTime (); 6 String dateStringParse = sdf. format (date); 7 // convert String to Date 8 String dateString = "11:11:11"; 9 date dateParse = sdf. parse (dateString); 10} catch (ParseException e) {11 e. printStackTrace (); 12}

Note:

  • You must specify the conversion format when creating the SimpleDateFormat object.
  • The conversion format is case sensitive. yyyy indicates the year, MM indicates the month, dd indicates the date, HH indicates the 24-digit hour, hh indicates the 12-digit hour, and mm indicates the minute, ss stands for seconds.
3. Date addition and subtraction

Generally, we perform two addition and subtraction operations on the date:

  • Based on a certain date, calculate the date before/after a few days, several years ago/after, or before or after other time units
    1 // calculate 2 Calendar now = Calendar based on the current time. getInstance (); 3 now. add (Calendar. YEAR, 1); // The current time after 1 YEAR 4 now. add (Calendar. YEAR,-1); // current time 1 YEAR ago 5 // calculate 6 Calendar YEAR specialDate = Calendar based on a specific time date (Date type. getInstance (); 7 specialDate. setTime (date); // note that the specialDate value is changed to the specified date 8 specialDate. add (Calendar. YEAR, 1); // a YEAR later than 9 specialDate. add (Calendar. YEAR,-1); // YEAR of a specific time

     

    Note that you can use the add method of the Calendar Object To Change Calendar. YEAR to any time unit field to complete date calculation under various time units.

  • Calculate the two time intervals, for example, the number of days between June 1 and June 1.
    1 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); 2 String dateString = "11:11:11"; 3 Calendar calendar = Calendar ar. getInstance (); 4 long nowDate = calendar. getTime (). getTime (); // Date. getTime () gets the millisecond-type date 5 try {6 long specialDate = sdf. parse (dateString ). getTime (); 7 long betweenDate = (specialDate-nowDate)/(1000*60*60*24); // calculate the number of days at which the interval is calculated, the conversion formula is 8 System divided by milliseconds to days. out. print (betweenDate); 9} catch (ParseException e) {10 e. printStackTrace (); 11}
4. Date comparison

Looking at your previous code, we found that every time you compare the date, we always convert the date to a string in the format of "yyyyMMdd", convert the string to a value, and then compare the value size. Haha, a simple comparison operation requires more than a dozen lines of code. Now let's talk about the correct date comparison posture.

Generally, there are two methods for Date comparison, which are common for java. util. Date or java. util. Calendar. One is to compare with the before () method, and the other is to compare with the compareTo () method.

SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); String dateString_01 = "11:11:11"; String dateString_02 = "11:11:11 "; try {Date date_01 = sdf. parse (dateString_01); Date date_02 = sdf. parse (dateString_02); System. out. println (date_01.before (date_02); // true, true if date_01 is less than date_02; otherwise, false System. out. println (date_02.after (date_01); // true, true if date_02 is greater than date_01; otherwise false System. out. println (date_01.compareTo (date_02); //-1. When date_01 is smaller than date_02, it is-1 System. out. println (date_02.compareTo (date_01); // 1. When date_02 is greater than date_01, it is 1 System. out. println (date_02.compareTo (date_02); // 0, 0} catch (ParseException e) {e. printStackTrace ();}
5. Recommended tool Libraries

I saw a friend who recommended the Joda-Time library to me. After research, I found that it can simplify many date-Time operations in Java, in some application scenarios, you must convert Date to Calendar or String to Date. The usage logic of the database is very similar to that of the native database, and the learning curve is still relatively smooth. Here, we also provide readers with a more diverse choice.

Joda-Time Website: http://www.joda.org/joda-time/

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.