During the development of Java, I was inevitably entangled with the Date type. I was going to summarize the date-related operations that the project often used. JDK version 1.7. If it can help you save a few minutes to get up and move and make a cup of coffee, it would be great. Hehe. Of course, I only provide viable solutions and are not guaranteed to be best practices, and discussions are welcome.
1. Date value
In the era of old JDK, there were many codes that used the java.util.Date class in terms of date values. However, since the Date class is not convenient to achieve internationalization, it is recommended to use the java.util.Calendar class for time and date processing starting from JDK1.1. I won't introduce the operations of the Date class here. Let's go straight to the topic and how to use the Calendar class to obtain the current date and time.
Since Calendar's constructor method is modified by protected, we will create a Calendar object through the getInstance method provided in the API.
//There are multiple overloaded methods to create Calendar objects Calendar now = Calendar.getInstance(); //Default//Specify the time zone and region, or you can only enter one of the parameters Calendar now = Calendar.getInstance(timeZone, locale);
Then we can obtain the current various time parameters through the object.
int year = now.get(Calendar.YEAR); //, current year int month = now.get(Calendar.MONTH) + ; //, current month, please add int day = now.get(Calendar.DATE); //, current day Date date = now.getTime(); // directly get a date of type 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:
•Calendar.DAY_OF_MONTH: Date, same as Calendar.DATE
•Calendar.HOUR: 12-hour hours
•Calendar.HOUR_OF_DAY: The number of hours in a 24-hour system
•Calendar.MINUTE: Minute
•Calendar.SECOND: seconds
•Calendar.DAY_OF_WEEK: Weekly
In addition to obtaining time data, we can also set various time parameters through the Calendar object.
//Set only the value of a certain field// public final void set(int field, int value) now.set(Calendar.YEAR, ); //Set year, month, day, hour, month, day, hour, minute, second// public final void set(int year, int month, int date[, int hourOfDay, int minute, int second]) now.set(, , [, , , ]); //Sign up a date of type Date directly// public final void setTime(Date date) now.set(date);
Notice:
•When the time parameter is set, other relevant values will be recalculated. For example, when you set the date to 11th, the corresponding changes will be made on the week.
•The month you get is plus 1. The actual month is the one.
•In the Calendar class, Sunday is 1, Monday is 2, and so on.
2. Date conversion
After chatting about the date, let’s talk about date conversion. The conversion is generally the mutual conversion between the Date-type date and the String-type string. I mainly use java.text.SimpleDateFormat for the 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 dateString = "-- ::"; 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 year, MM represents month, dd represents date, HH represents hour in 2011, hh represents hour in 1011, mm represents minute, and ss represents seconds.
3. Date addition and subtraction
Generally speaking, we will do two additions and subtraction operations on dates:
• Based on a date, calculate the dates before/after, before/after, or before/after, or before and after other time units.
// Calculate Calendar now = Calendar.getInstance(); now.add(Calendar.YEAR, ); // After the year of the current time now.add(Calendar.YEAR, -); // Before the year of the current time// Calculate Calendar specialDate = Calendar.getInstance(); specialDate.setTime(date); // Note that the value of specialDate is changed to a specific date specialDate.add(Calendar.YEAR, ); // After the year of the specific time specialDate.add(Calendar.YEAR, -); // Before the year of the specific time
Note that the add method of the Calendar object is used. You can change Calendar.YEAR to any time unit field to complete the date calculation under various time units.
• Calculate the interval between two times, for example, how many days are there now on January 1, 2016.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = "-- ::"; 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) / ( * * * ); // Calculate how many days apart, divide it by the conversion formula of milliseconds to days System.out.print(betweenDate); } catch (ParseException e) { e.printStackTrace(); } 4. Date comparison
Looking through my previous code, I found that whenever I perform a date comparison operation, I will first convert the date to a string in the format "yyyyMMdd", then convert the string to a value, and then compare the value size. Haha, it’s a simple comparison operation, but it takes more than a dozen lines of code to write, which is a bit unbearable. Now we have to talk about the correct date comparison posture.
There are generally two methods for date comparison, which are common for java.util.Date or java.util.Calendar. One is to compare with the before() method through after(), and the other is to compareTo() method through the comparisonTo() 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, when date_01 is less than date_02 When it is true, otherwise it is false System.out.println(date_02.after(date_01)); //true, when date_02 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, 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, it is 0} catch (ParseException e) { e.printStackTrace();}The above is the full description of common date operations (value, conversion, addition and subtraction, comparison) in Java introduced to you in this article. I hope you like it.