The common date operations in Java are of value conversion addition and subtraction and comparison

  • 2020-04-01 04:32:14
  • OfStack

Java DeKaiFaGuoChengZhongMianBuLeYu Date Type entanglement, ready to summarize the date related operations that the project often USES, JDK If you can save everyone a few minutes to get up and move to make a cup of coffee, then  It's great, heh. version 1.7 Of course, I only offer a viable solution, not a guarantee of best practice, and welcome the discussion.

1. Date value

in  The old version JDK Time, there are a lot of code to take advantage of the date value java.util.Date Class, but because Date Classes are not easy to achieve internationalization, actually from JDK1.1 In the beginning, it is more recommended java.util.Calendar Class handles the time and date aspects. Instead of covering the operations of the Date class, let's get straight to the point of using the Calendar class to get the current Date time.

Since the Calendar constructor method is protected, we create the Calendar object through the getInstance method provided in the API.


 // There are  Multiple overloaded methods are created  Calendar object
 Calendar now = Calendar.getInstance(); //The default
 //Specify the time zone and locale, or enter only one of the parameters
 Calendar now = Calendar.getInstance(timeZone, locale); 

Then we can get the current various time parameters from this object.


int year = now.get(Calendar.YEAR); //, current year
int month = now.get(Calendar.MONTH) + ; //, current month, pay attention to add
int day = now.get(Calendar.DATE); // , the current day Date date = now.getTime(); // Get one directly  Date  Type of date  

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

  The & # 8226; Calendar.day_of_month: same as calendar.date
  The & # 8226; Calendar.HOUR: the number of hours on a 12-hour schedule
  The & # 8226; Calendar.hour_of_day: the number of hours in a 24-hour system
  The & # 8226; Calendar. MINUTE: minutes
  The & # 8226; Calendar. SECOND: seconds
  The & # 8226; Calendar. DAY_OF_WEEK: several weeks

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


//Set the value of only one field
 // public final void set(int field, int value)
 now.set(Calendar.YEAR, );
 //Set the date of the year or the time of the day of the month or the minute of the day of the month
 // public final void set(int year, int month, int date[, int hourOfDay, int minute, int second])
 now.set(, , [, , , ]);
 //Directly pass in a Date of type Date
 // public final void setTime(Date date)
 now.set(date); 

Note:

  The & # 8226; When the time parameter is set, other relevant values are recalculated. For example, when you set the date to 11th, the week will change accordingly.
  The & # 8226; The month you get plus 1 is the actual month.
  The & # 8226; In the Calendar class, Sunday is 1, Monday is 2, and so on.

2. Date conversion

With the value Date, then talk about the Date conversion, type conversion is generally the Date Date and mutual transformation between String String type, I mainly use Java. The text. The SimpleDateFormat conversion operation.


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 try {
   //Date to 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();   
 } 

Note:

  The & # 8226; You must specify the conversion format when you create the SimpleDateFormat object.

  The & # 8226; The conversion format is case sensitive, yyyy for year, MM for month, dd for date, HH for 24 base hours, HH for 12 base hours, MM for minutes, ss for seconds.

3. Date plus or minus

In general, there are two ways to add and subtract dates:

  The & # 8226; Use a date as a benchmark to calculate the date before/after a few days ago/after a few years ago/after, or before and after other time units


 //Based on the present time
 Calendar now = Calendar.getInstance(); 
 now.add(Calendar.YEAR, ); //Years from now
 now.add(Calendar.YEAR, -); //The present time is years ago
 //Based on a particular date of time
 Calendar specialDate = Calendar.getInstance();
 specialDate.setTime(date); //Notice that here you change the value of specialDate to a specific date
 specialDate.add(Calendar.YEAR, ); //Years after a certain time
 specialDate.add(Calendar.YEAR, -); // Years before a particular time  

ZhuYiShiYongLe Calendar DuiXiangDe add Method, which can be changed Calendar.YEAR Is the arbitrary time unit field,  Complete date calculations in various time units.

The & # 8226; Calculate the interval between two times, such as the number of days from January 1, 2016 to the present.


 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) / ( * * * ); //To calculate the number of days, divide by the conversion formula of milliseconds to days
     System.out.print(betweenDate);
 } catch (ParseException e) {
     e.printStackTrace();
 }  

4. Date comparison

Looking back at my previous code, I found that whenever I did a date comparison, I always converted the date to a string in "yyyyMMdd" format, converted the string to a value, and then compared the value. Ha ha, a simple comparison operation, but to write a dozen lines of code, a bit unbearable. Now let's talk about what the correct date comparison posture is.

There are generally two methods of Date comparison, which are common for java.util.date or java.util.calendar. One is to compare after() with before(), and the other is to compare with compareTo().


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 is true when date_01 is less than date_02, or false otherwise
    System.out.println(date_02.after(date_01)); //True is true when date_02 is greater than date_01, or false otherwise
    System.out.println(date_01.compareTo(date_02)); //-1 is -1 when date_01 is less than date_02
    System.out.println(date_02.compareTo(date_01)); //1, is 1 when date_02 is greater than date_01
    System.out.println(date_02.compareTo(date_02)); //Zero, when two dates are equal, is zero
} catch (ParseException e) {
    e.printStackTrace();
}

The above is the full description of the common date operations (value, transform, add and subtract, compare) in Java introduced in this article. I hope you enjoy it.


Related articles: