Several common operations on dates in Java: value, conversion, addition, subtraction, and comparison

Source: Internet
Author: User

Several common operations on dates in Java: value, conversion, addition, subtraction, and comparison

 

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.

// There are multiple overload methods to create a Calendar Object
Calendar now = Calendar. getInstance (); // default
// Specify the time zone and region. You can also enter only one of the parameters.
Calendar now = Calendar. 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, for the current month, add 1
Int day = now. 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.

// Only set the value of a field
// Public final void set (int field, int value)
Now. set (Calendar. YEAR, 2016 );
// Set the hour, month, day, year, month, month, day, hour, minute, and second.
// Public final void set (int year, int month, int date [, int hourOfDay, int minute, int second])
Now. set (2016, 1, 1 [, 11, 1, 1]);
// Input a Date directly.
// Public final void setTime (Date date)
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.

SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
Try {
// Convert date to string
Calendar calendar = Calendar. getInstance ();
Date date = calendar. getTime ();
String dateStringParse = sdf. format (date );
// String to date
String dateString = "11:11:11 ";
Date dateParse = sdf. parse (dateString );
} Catch (ParseException e ){
E. printStackTrace ();
}

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

// Calculated based on the current time
Calendar now = Calendar. getInstance ();
Now. add (Calendar. YEAR, 1); // one YEAR after the current time
Now. add (Calendar. YEAR,-1); // 1 YEAR before the current time
// Calculated based on a specific time date (Date type)
Calendar specialDate = Calendar. getInstance ();
SpecialDate. setTime (date); // change the value of specialDate to a specific date.
SpecialDate. add (Calendar. YEAR, 1); // one YEAR after a specific time
SpecialDate. add (Calendar. YEAR,-1); // a YEAR before 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.

SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss ");
String dateString = "11:11:11 ";
Calendar calendar = Calendar. getInstance ();
Long nowDate = calendar. getTime (). getTime (); // Date. getTime () Get the Date in milliseconds
Try {
Long specialDate = sdf. parse (dateString). getTime ();
Long betweenDate = (specialDate-nowDate)/(1000*60*60*24); // the formula for calculating the number of days between milliseconds and days.
System. out. print (betweenDate );
} Catch (ParseException e ){
E. printStackTrace ();
}

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 smaller 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 less 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. When two dates are equal
} Catch (ParseException e ){
E. printStackTrace ();
}

 

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.