java date type operation

1. Date value

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

1  // There are multiple overloaded methods to create Calendar objects 
2 Calendar now = Calendar.getInstance(); // Default
 3  // Specify the time zone and region, or you can enter only one of the parameters 
4 Calendar now = Calendar.getInstance(timeZone, locale);

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

int year = now.get(Calendar.YEAR); //2015, current year 
int month = now.get(Calendar.MONTH) + 1; //12, current month, add 1 
int day = now.get(Calendar .DATE); //23, the current day
Date date = now.getTime(); //Get a Date type date directly

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:

  • Calendar.DAY_OF_MONTH: date, same as Calendar.DATE
  • Calendar.HOUR: Hour in 12-hour clock
  • Calendar.HOUR_OF_DAY: Hours in 24-hour clock
  • Calendar.MINUTE: minutes
  • Calendar.SECOND: seconds
  • Calendar.DAY_OF_WEEK: Day of the week

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

copy code
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 the year, month, day or year, month, day, hour and minute 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 pass in a date of type Date
 8  // public final void setTime(Date date) 
9 now.set(date);
copy code

Notice:

  • When the time parameter is set, other related values ​​will be recalculated. For example, when you set the date to the 11th, the day of the week will change accordingly.
  • 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

Mainly use java.text.SimpleDateFormat for conversion operations.

copy code
 1 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 2 try {
 3     //日期转字符串
 4     Calendar calendar = Calendar.getInstance();
 5     Date date = calendar.getTime();
 6     String dateStringParse = sdf.format(date);
 7     //字符串转日期
 8     String dateString = "2016-01-01 11:11:11";
 9     Date dateParse = sdf.parse(dateString);
10 } catch (ParseException e) {
11      e.printStackTrace();      
12 }
copy code

Notice:

  • The conversion format must be specified when creating a SimpleDateFormat object.
  • The conversion format is case-sensitive, yyyy represents the year, MM represents the month, dd represents the date, HH represents the hour in 24, hh represents the hour in 12, mm represents minutes, and ss represents seconds.

3. Date addition and subtraction

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

  • Based on a date, calculate the date in days before/after, years before/after, or other time units
    copy code
    1  // Calculate according to the current time 
    2 Calendar now = Calendar.getInstance(); 
     3 now.add(Calendar.YEAR, 1); // 1 year after the current time 
    4 now.add(Calendar.YEAR, -1); // 1 year ago
     5 of the current time  // Calculate 6 according to a specific time date (Date type)
     Calendar specialDate = Calendar.getInstance();
     7 specialDate.setTime(date); // Note that the specialDate's Change the value to a specific date 8 specialDate.add(Calendar.YEAR, 1); // 1 year after a specific time 9 specialDate.add(Calendar.YEAR, -1); // 1 year before a specific time
    
    
    copy code

     

    Note that using the add method of the Calendar object, Calendar.YEAR can be changed to any time unit field to complete the date calculation under various time units.

  • Calculate the interval between two times, such as calculating how many days are now until January 1, 2016.
    copy code
    1 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
     2 String dateString = "2016-01-01 11:11:11" ;
     3 Calendar calendar = Calendar.getInstance();
     4  long nowDate = calendar.getTime().getTime(); // Date.getTime() get millisecond date 
    5  try {
     6         long specialDate = sdf.parse(dateString).getTime();
     7         long betweenDate = (specialDate - nowDate) / (1000 * 60 * 60 * 24); // Calculate how many days the interval is, then divide by the conversion formula from milliseconds to days 
    8          System.out.print(betweenDate);
     9 }catch (ParseException e) {
    10          e.printStackTrace();
    11 }  

4. Date comparison

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

copy code
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, when date_01 is less than date_02, true, otherwise false 
       System.out.println(date_02.after(date_01)); // true, when date_02 When it is greater than date_01, it is true, otherwise it is 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, 1 when date_02 is greater than date_01 
       System.out.println(date_02.compareTo(date_02)); // 0, 0 when both dates are equal 
} catch (ParseException e) {
        e.printStackTrace ();
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325726407&siteId=291194637