Several common operations for dates in Java--value, conversion, subtraction, Comparison

Source: Internet
Author: User
Tags time and date

Java development process inevitably with the date type entanglement, ready to summarize the project frequently used date related operations, JDK version 1.7, if can help everyone save a few minutes to get up activities, to brew a cup of coffee, is very good, hey. Of course, I only offer a workable solution, not guaranteed to be a best practice, welcome to the discussion.

1. Date value

In the old version of the JDK era, there are many code in the date value of the use of the Java.util.Date class, but because the date class is not easy to achieve internationalization, in fact, starting from JDK1.1, it is recommended to use the Java.util.Calendar class for time and date processing. This does not describe the operation of the date class, let's go straight to the topic, how to use the Calendar class to get the current date and time.

Because the constructor method of the calendar is protected decorated, we will create the Calendar object through the GetInstance method provided in the API.

// There are multiple overloaded methods to create a Calendar object // default // Specify a time zone and region, or you can enter only one of the parameters Calendar now = calendar.getinstance (timeZone, locale);

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

int // 2015, Current year int // 12, Current month, note plus 1 int // 23, Current day // get a date type directly

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

    • Calendar.day_of_month: Date, same as Calendar.date
    • Number of hours calendar.hour:12 hours
    • Number of hours calendar.hour_of_day:24 hours
    • Calendar.minute: Minutes
    • Calendar.second: Sec
    • Calendar.day_of_week: Zhou

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

// set the value of a field only // Public final void set (int field, int value)now.set (Calendar.year); // Set month day or month day or month day time // Public final void set (int year, int month, int date[, int hourofday, int minute, int second])Now.set (2016, 1, 1[ , one, 1, 1]); // a date that is passed directly to a date type // Public final void settime (date date)now.set (date);

Attention:

    • When the time parameter is set, the other related values are recalculated, for example, when you set the date to 11th, the week will change accordingly.
    • The month plus 1 obtained is the actual month.
    • In the Calendar class, Sunday is 1, Monday is 2, and so on.
2. Date conversion

Chat The date value, next chat date conversion, conversion is generally the date type and string string of the conversion between, I mainly use Java.text.SimpleDateFormat for conversion operations.

New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Try {    // date to string    Calendar calendar = calendar.getinstance ();     = calendar.gettime ();     = Sdf.format (date);     // string to date    String datestring = "2016-01-01 11:11:11";     =catch  (ParseException e) {     e.printstacktrace ();      }

Attention:

    • You must specify a conversion format when you create a SimpleDateFormat object.
    • The conversion format is case-sensitive, yyyy for the year, MM for the month, DD for the date, HH for the 24-hour, HH for 12-hour, MM for minutes, and SS for seconds.
3. Date plus minus

In general, we do two add and subtract operations on dates:

Calculates the day before/after, several years before/after, or before or after a certain date

 //  According to the current time calculation  Calendar now = Calendar.getinstance (); Now.add (Calendar.year,  1); //  Now.add (Calendar.year,-1); //  Now 1 years ago  //  is calculated based on a specific time date (date type). Calendar specialdate = Calendar.getinstance (); Specialdate.settime (date);  //  note here to change the value of specialdate to a specific date  specialdate.add (calendar.year, 1); //  specialdate.add (Calendar.year,-1); //  

Note using the Add method of the Calendar object, you can change the calendar.year to any time unit field to complete the calculation of the date under various time units.

Calculates a two-time interval, such as how many days the January 1, 2016 distance is now.

SimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String datestring= "2016-01-01 11:11:11"; Calendar Calendar=calendar.getinstance ();LongNowdate = Calendar.gettime (). GetTime ();//Date.gettime () Gets the millisecond type dateTry {       LongSpecialdate =Sdf.parse (datestring). GetTime (); LongBetweendate = (specialdate-nowdate)/(1000 * 60 * 60 * 24);//calculate the interval in days, divided by the conversion formula of milliseconds to daysSystem.out.print (betweendate);} Catch(ParseException e) {e.printstacktrace ();}
4. Date comparison

Look at your previous code and find that whenever you perform a date comparison, the date is converted to a "YYYYMMDD" string, the string is converted to a numeric value, and then the value size is compared. Haha, a simple comparison operation, but to write more than 10 lines of code, a little eye can not bear to be seen. Now it's time to talk about the correct date comparison posture.

Date comparisons generally have two methods, which are common for java.util.Date or Java.util.Calendar. One is compared by the After () with the Before () method, and one by the CompareTo () method.

SimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String datestring_01= "2016-01-01 11:11:11"; String datestring_02= "2016-01-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 when date_01 is less than date_02, true, otherwise falseSystem.out.println (Date_02.after (date_01));//true, True if date_02 is greater than date_01, otherwise falseSystem.out.println (Date_01.compareto (date_02));//-1, when date_01 is less than date_02, 1System.out.println (Date_02.compareto (date_01));//1, when date_02 is greater than date_01, 1System.out.println (Date_02.compareto (date_02));//0, when two dates are equal, 0}Catch(ParseException e) {e.printstacktrace ();}

Several common operations for dates in Java--value, conversion, subtraction, Comparison

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.