Java Get the time difference between two times
In normal work, it is inevitable that you will encounter the difference in days, hours, minutes, seconds, and milliseconds between two times. Now I summarize the methods I obtain as follows:
1. Import the required dependencies
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>4.6.10</version> </dependency>
2. Description of the method
## How many days is the difference between date1 and date2 DateUtil.between(date1, date2, DateUnit.DAY); ## How many hours is the difference between date1 and date2 DateUtil.between(date1, date2, DateUnit.HOUR); ## How many minutes is the difference between date1 and date2 DateUtil. between(date1, date2, DateUnit. MINUTE); ## How many seconds is the difference between date1 and date2 DateUtil. between(date1, date2, DateUnit. SECOND); ## How many milliseconds is the difference between date1 and date2 DateUtil.between(date1, date2, DateUnit.MS);
3. Method testing
public class DateTest { public static void main(String[] args) { Date data1 = DateUtil. parse("2022-09-07 12:23:25"); Date date2 = DateUtil. parse("2022-09-07 18:23:25"); System.out.println("Difference between two times "+DateUtil.between(data1, date2, DateUnit.DAY)+" days"); System.out.println("Difference between two times "+DateUtil.between(data1, date2, DateUnit.HOUR)+" hours"); System.out.println("Difference between two times "+DateUtil.between(data1, date2, DateUnit.MINUTE)+" minutes"); System.out.println("Difference between two times "+DateUtil.between(data1, date2, DateUnit.SECOND)+" seconds"); System.out.println("Difference between two times "+DateUtil.between(data1, date2, DateUnit.MS)+" milliseconds"); } }
Fourth, the console output is as follows
There is a difference of 0 days between the two times 6 hours difference between the two times The difference between the two times is 360 minutes The difference between the two times is 21600 seconds The difference between the two times is 21600000 milliseconds
5. Method extension
## Convert string time to Date type output: 2022-09-07 12:23:25 DateUtil. parse("2022-09-07 12:23:25"); ## Convert Date type to string time Output: 2022-09-07 16:42:05 DateUtil. format(new Date(), "yyyy-MM-dd HH:mm:ss");
0 Comments