Home  >  Article  >  Java  >  Common date operations in Java (value acquisition, conversion, addition, subtraction, comparison)

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

高洛峰
高洛峰Original
2017-01-20 16:33:191377browse

In the development process of Java, it is inevitable to get entangled with the Date type. I am going to summarize the date-related operations frequently used in the project. JDK version 1.7. If it can help everyone save a few minutes to get up and move around and make a cup of coffee, it will be great. Okay, hehe. Of course, I only provide feasible solutions and do not guarantee best practices. Discussions are welcome.

1. Date value

In the era of the old version of JDK, there were many codes that used the java.util.Date class to obtain date values, but due to The Date class is not convenient for internationalization. In fact, starting from JDK1.1, it is more recommended to use the java.util.Calendar class for time and date processing. We won’t introduce the operations of the Date class here. Let’s 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.

//有多个重载方法创建 Calendar 对象
Calendar now = Calendar.getInstance(); //默认
//指定时区和地区,也可以只输入其中一个参数
Calendar now = Calendar.getInstance(timeZone, locale);

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

int year = now.get(Calendar.YEAR); //,当前年份
int month = now.get(Calendar.MONTH) + ; //,当前月,注意加
int day = now.get(Calendar.DATE); //,当前日Date date = now.getTime(); //直接取得一个 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, the same as Calendar.DATE
•Calendar.HOUR: Hours in 12-hour format
•Calendar.HOUR_OF_DAY: Hours in 24-hour format
•Calendar.MINUTE: Minutes
•Calendar.SECOND: Seconds
•Calendar.DAY_OF_WEEK: Day of the week

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

//只设定某个字段的值
 // public final void set(int field, int value)
 now.set(Calendar.YEAR, );
 //设定年月日或者年月日时分或年月日时分秒
 // public final void set(int year, int month, int date[, int hourOfDay, int minute, int second])
 now.set(, , [, , , ]);
 //直接传入一个 Date 类型的日期
 // public final void setTime(Date date)
 now.set(date);

Note:

•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 Corresponding changes will be made.
•Add 1 to the obtained month to get the actual month.
•In the Calendar class, Sunday is 1, Monday is 2, and so on.

2. Date conversion

After talking about date value, let’s talk about date conversion. The conversion is usually the interaction between Date type date and String type string. For conversion, I mainly use java.text.SimpleDateFormat for conversion operations.

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 = "-- ::";
   Date dateParse = sdf.parse(dateString);
 } catch (ParseException e) {
   e.printStackTrace();  
 }

Note:

•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 24-base hour, hh represents the 12-base hour, mm represents the minute, and ss represents Second.

3. Date addition and subtraction

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

•With a certain A date is used as a basis to calculate the days before/after, years before/after, or the dates before and after other time units

//根据现在时间计算
Calendar now = Calendar.getInstance();
now.add(Calendar.YEAR, ); //现在时间的年后
now.add(Calendar.YEAR, -); //现在时间的年前
//根据某个特定的时间 date (Date 型) 计算
Calendar specialDate = Calendar.getInstance();
specialDate.setTime(date); //注意在此处将 specialDate 的值改为特定日期
specialDate.add(Calendar.YEAR, ); //特定时间的年后
specialDate.add(Calendar.YEAR, -); //特定时间的年前

Note that the add method of the Calendar object is used, which can be changed Calendar.YEAR is an arbitrary time unit field, completing date calculations in various time units.

•Calculate the interval between two times, for example, calculate how many days are there between January 1, 2016 and now.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = "-- ::";
Calendar calendar = Calendar.getInstance();
long nowDate = calendar.getTime().getTime(); //Date.getTime() 获得毫秒型日期
try {
    long specialDate = sdf.parse(dateString).getTime();
    long betweenDate = (specialDate - nowDate) / ( * * * ); //计算间隔多少天,则除以毫秒到天的转换公式
    System.out.print(betweenDate);
} catch (ParseException e) {
    e.printStackTrace();
}

 

#4. Date comparison

Looking through my previous code, I found that whenever a date comparison operation is performed When doing this, the date will always be converted into a string in the "yyyyMMdd" format, then the string will be converted into a numerical value, and then the numerical values ​​will be compared. Haha, a simple comparison operation requires writing more than ten lines of code, which is a bit overwhelming. Now let’s talk about the correct way to compare dates.

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,当 date_01 小于 date_02 时,为 true,否则为 false
    System.out.println(date_02.after(date_01)); //true,当 date_02 大于 date_01 时,为 true,否则为 false
    System.out.println(date_01.compareTo(date_02)); //-1,当 date_01 小于 date_02 时,为 -1
    System.out.println(date_02.compareTo(date_01)); //1,当 date_02 大于 date_01 时,为 1
    System.out.println(date_02.compareTo(date_02)); //0,当两个日期相等时,为 0
} catch (ParseException e) {
    e.printStackTrace();
}

The above is the complete description of common date operations (value acquisition, conversion, addition, subtraction, comparison) in Java introduced in this article. I hope you like it.

For more articles related to common date operations in Java (value acquisition, conversion, addition, subtraction, comparison), please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn