Common date operations in Java (value, conversion, addition, subtraction, comparison) _java

Source: Internet
Author: User
Tags numeric value time and date

Java development process is unavoidable with the date type of entanglement, ready to summarize the project often used by date-related operations, JDK version 1.7, if it can help you save a few minutes to get up and go to a cup of coffee, is very good, hey. Of course, I only offer a workable solution, not a guarantee of best practices, and welcome discussion.

1. Date value

In the old version of JDK, there was a lot of code in which the date value took advantage of the Java.util.Date class, but since the date class was not easy to internationalize, it was more recommended to use the Java.util.Calendar class for time and date processing, starting with JDK1.1. This does not introduce the date class, let's go straight to the topic, how to use the Calendar class to get the current date time.

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

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

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

int year = Now.get (calendar.year); , Current year
int month = Now.get (calendar.month) +;//, Current month, note plus 

To obtain other types of time data only need to modify the parameters in 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: Week

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

Set only the value of a field
 //public final void set (int field, int value)
 now.set (Calendar.year,);
 Set the date or year of the day or year or year/day time seconds
 //public final void set (int year, int month, int date[, int hourofday, int minute, int second])
 Now.set (,, [,,,,]);
 Pass directly to a date of type dates
 //public final void settime (date date)
 

Attention:

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

2. Date conversion

Talk about the date value, then talk about date conversion, the conversion is generally a date date and string string between the conversion, I mainly use Java.text.SimpleDateFormat for conversion operations.

SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
 try {
   //date-turn string
   Calendar calendar = calendar.getinstance ();
   Date date = Calendar.gettime ();
   String Datestringparse = Sdf.format (date);
   String to date
   string datestring = "--::";
   Date dateparse = Sdf.parse (datestring);
 } catch (ParseException e) {
   e.printstacktrace ();   
 

Attention:

• The conversion format must be specified when creating the SimpleDateFormat object.

• The conversion format is case-sensitive, YYYY represents the year, MM represents the month, DD represents the date, and HH represents the 24-hour, and HH stands for 12-hour, mm for minutes, and SS for seconds.

3. Date plus minus

Generally, we do two kinds of addition and subtraction operations on dates:

• Calculates the date before/after, several years ago/after, or other time units, on a date basis

 Calculates the Calendar now
 = Calendar.getinstance () based on the current time; 
 Now.add (Calendar.year,); The time of the year is now
 Now.add (Calendar.year,-);//Now years ago
 //The Calendar is calculated according to a specific time date (date type)
 Specialdate = Calendar.getinstance ();
 Specialdate.settime (date); Note Here to change the value of specialdate to a specific date
 Specialdate.add (calendar.year,);//After a certain time of year
 

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

• Calculate two-time intervals, such as how many days the January 1, 2016 distance is now.

 SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
 String datestring = "--::";
 Calendar calendar = Calendar.getinstance ();
 Long nowdate = Calendar.gettime (). GetTime (); Date.gettime () Gets the millisecond date
 try {
     long specialdate = Sdf.parse (datestring). GetTime ();
     Long betweendate = (specialdate-nowdate)/(* * *); How many days interval is calculated, divided by milliseconds to day conversion formula
     System.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, you will first change the date to a "YyyyMMdd" string, then convert the string to a numeric value, and then compare the numeric size. Haha, a simple comparison operation, but to write more than 10 lines of code, a little eyes can not bear to view. Now it's time to say exactly what the date comparison posture is.

There are generally two ways to compare dates, which are common to java.util.Date or Java.util.Calendar. One is through the after () and before () method comparison, one is through the CompareTo () method for comparison.

SimpleDateFormat SDF = new SimpleDateFormat ("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, True if date_01 is less than date_02, otherwise false
    System.out.println (Date_02.after (date_01));//true when date_02 is greater than date_ 01 o'clock, True, otherwise false
    System.out.println (Date_01.compareto (date_02));//-1, when date_01 is less than date_02, 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, 0
} catch ( ParseException e) {
    e.printstacktrace ();
}

The above is the Java in this article to introduce common date operations (value, conversion, addition and subtraction, comparison) of all the narrative, I hope you like.

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.