Dates are commonly used in java

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

In the development process of Java, it is inevitable to be entangled with the Date type. I am going to summarize the date-related operations that are often used in the project. JDK version 1.7, if it can help you save a few minutes, get up and move around and make a cup of coffee. It is excellent, hehe . Of course, I only provide a feasible solution, not guaranteed to be the best practice, welcome to discuss.

Author: Source: Honoka_Sunny Day |2015-12-25 10:44

Award-winning research | 1TB hard disk is waiting for you to take the development trend and application research of AI + blockchain


 

In the development process of Java, it is inevitable to be entangled with the Date type. I am going to summarize the date-related operations that are often used in the project. JDK version 1.7, if it can help you save a few minutes, get up and move around and make a cup of coffee. It is excellent, hehe . Of course, I only provide a feasible solution, not guaranteed to be the best practice, welcome to discuss.

1. Date value

In the era of the old version of JDK, many codes used the java.util.Date class for date values. However, since the Date class is inconvenient for internationalization, since JDK1.1, it is more recommended to use java.util.Calendar The class handles time and date processing. The operation of the Date class will not be introduced here, let us go straight to the topic, how to use the Calendar class to obtain the current date and time.

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

//There are multiple overloaded methods to create 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 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.

//Only set the value of a field
// public final void set(int field, int value)
now.set(Calendar.YEAR, 2016);
//Set the year, month, day, or year, month, day, hour, or year, month, day hour, minute, 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]);
// Directly pass in a date of type Date
// public final void setTime(Date date)
now.set(date);

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

After talking about the date value, let's talk about the date conversion. The conversion is generally the conversion between Date type date and String type string. I mainly use java.text.SimpleDateFormat for conversion operation.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    //日期转字符串
    Calendar calendar = Calendar.getInstance();
    Date date = calendar.getTime();
    String dateStringParse = sdf.format(date);
    //字符串转日期
    String dateString = "2016-01-01 11:11:11";
    Date dateParse = sdf.parse(dateString);
} catch (ParseException e) {
     e.printStackTrace();      
}

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

//Calculate
Calendar according to the current time now = Calendar.getInstance(); 
now.add(Calendar.YEAR, 1); //1 year after the current time
now.add(Calendar.YEAR, -1); //Current time 1 year ago
//Calculate Calendar 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, 1); //1 year after a specific time
specialDate.add(Calendar.YEAR, -1); //1 year before a specific time

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.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = "2016-01-01 11:11:11";
Calendar calendar = Calendar.getInstance();
long nowDate = calendar. getTime().getTime(); //Date.getTime() get millisecond date
try {
       long specialDate = sdf.parse(dateString).getTime();
       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
        System.out.print(betweenDate);
} catch (ParseException e) {
         e.printStackTrace();
}

4. Date comparison

Looking at my previous code, I found that whenever a date comparison operation is performed, the date is always converted into a string in the format of "yyyyMMdd", and then the string is converted into a numerical value, and then the numerical value is compared. Haha, a simple comparison operation requires more than a dozen lines of code, which is a bit unbearable. Now let's talk about what the correct date comparison posture looks like.

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.

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 when 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, true, 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, 0 when the two dates are equal
} catch (ParseException e) {
        e.printStackTrace();
}

Guess you like

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