如何在Java中计算两个日期之间的时间差

如何在Java中计算两个日期之间的时间差

我们面临的挑战是使用Java语言来确定两个日期之间的差异。

给出两个日期的开始日期以及结束日期,时间以字符串表示。

例1 :

输入以下日期。

开始日期=10/01/2018 01:10:20。

结束日期=10/06/2020 06:30:50。

输出结果。2,152天,5,20,30秒,或5,20小时。

例2 :

输入以下日期。

开始日期和结束日期:10-01-2019和06-06-2020

结果。152天,5小时,0分钟和0秒。

使用Java SimpleDateFormat类

要比较两个日期,请使用SimpleDateFormat和Date类。以下步骤。

  1. 通过创建SimpleDateFormat类的一个实例,将字符串格式转换为日期对象。
  2. 要创建一个日期,使用simpleDateFormat类的parse()方法从一个字符串中提取起始日期和结束日期。
  3. 使用Java方法getTime()作为d2.getTime()-d1.getTime,确定两个日期之间的时间差,以毫秒为单位()。
  4. 为了确定两个日期之间的差异,使用日期-时间数学公式。返回两个指定日期之间的年、日、小时、分钟和秒。
  5. 打印完成的产品。

上述策略的实践情况如下。

文件名:TimeDiff1.java

// Java code for the method described above

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

class TimeDiff1 {

    // method for printing the difference between the
    // startdate as well as the enddate
    static void
    findDiff(String startdate,
                   String enddate)
    {

        // SimpleDateFormat is used for converting the
        // string format into the date instance
        SimpleDateFormat sdf1
            = new SimpleDateFormat(
                "dd-MM-yyyy HH:mm:ss");

        // Try Block
        try {

            // parse method is used for parsing
            // the text from a string to
            // produce the date
            Date d0 = sdf1.parse(startdate);
            Date d1 = sdf1.parse(enddate);

            // Calculating the time difference
            // in milliseconds
            long Time_difference
                = d0.getTime() - d1.getTime();

            // Calculating the time difference in
            // terms of seconds, minutes, hours, years,
            // and days
            long Seconds_difference
                = (Time_difference
                   / 1000)
                  % 60;

            long Minutes_difference
                = (Time_difference
                   / (1000 * 60))
                  % 60;

            long Hours_difference
                = (Time_difference
                   / (1000 * 60 * 60))
                  % 24;

            long Years_difference
                = (Time_difference
                   / (1000l * 60 * 60 * 24 * 365));

            long Days_difference
                = (Time_difference
                   / (1000 * 60 * 60 * 24))
                  % 365;

            // Printing the difference between the dates in terms of
            // years, in days, in hours, in
            // seconds, as well as in minutes

            System.out.print(
                "Difference "
                + "between the two dates is: ");

            System.out.println(
                Years_difference
                + " years, "
                + Days_difference
                + " days, "
                + Hours_difference
                + " hours, "
                + Minutes_difference
                + " minutes, "
                + Seconds_difference
                + " seconds");
        }

        // Catching the Exception
        catch (ParseException e) {
            e.printStackTrace();
        }
    }

    // Main Code
    public static void main(String args[])
    {
        // user Start Date
        String startdate
            = "11-01-2018 02:11:20";

        // user end Date
        String enddate
            = "11-06-2020 07:31:50";

        // Method Call
        findDiff(startdate, enddate);
    }
}

输出

The difference between the two dates is: -2 years, -152 days, -5 hours, -20 minutes, -30 seconds

使用Java TimeUnit类

通过使用Java内置的TimeUnit类,我们可以更准确地确定两个日期之间的差异。上述方法的实际应用如下。

文件名:TimeDiff2.java

// Java program for calculating the
// difference between the two dates

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.Date;

class TimeDiff2 {

    // Method for printing the difference between
    // startdate as well as enddate
    static void findDiff(String startdate,
                               String enddate)
    {
        // SimpleDateFormat for converting the
        // string format into the date instance
        SimpleDateFormat sdf1
            = new SimpleDateFormat(
                "dd-MM-yyyy HH:mm:ss");

        // using the Try block
        try {

            // parse method is used for parsing
            // the text from a string for
            // producing the date
            Date d0 = sdf1.parse(startdate);
            Date d1 = sdf1.parse(enddate);

            // Calculating the time difference
            // in milliseconds
            long Time_difference
                = d1.getTime() - d0.getTime();

            // Calculating the time difference in terms of minutes, 
            // hours, seconds, years, and days
            long Seconds_difference
                = TimeUnit.MILLISECONDS
                      .toSeconds(Time_difference)
                  % 60;

            long Minutes_difference
                = TimeUnit
                      .MILLISECONDS
                      .toMinutes(Time_difference)
                  % 60;

            long Hours_difference
                = TimeUnit
                      .MILLISECONDS
                      .toHours(Time_difference)
                  % 24;

            long Days_difference
                = TimeUnit
                      .MILLISECONDS
                      .toDays(Time_difference)
                  % 365;

            long Years_difference
                = TimeUnit
                      .MILLISECONDS
                      .toDays(Time_difference)
                  / 365l;

            // Printing the date difference in
            // terms of years, in terms of days, in terms of hours, in terms of
            // minutes, and in terms of seconds
            System.out.print(
                "Difference"
                + " between the two dates is: ");

            // Printing the result
            System.out.println(
                Years_difference
                + " years, "
                + Days_difference
                + " days, "
                + Hours_difference
                + " hours, "
                + Minutes_difference
                + " minutes, "
                + Seconds_difference
                + " seconds");
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
    }

    // Main Code
    public static void main(String args[])
    {
        // User start_date
        String startdate
            = "11-01-2018 02:10:20";

        // User end_date
        String enddate
            = "10-06-2020 06:30:50";

        // Main Call
        findDiff(startdate,
                       enddate);
    }
}

输出

The difference between the two dates is: 2 years, 151 days, 4 hours, 20 minutes, 30 seconds

使用Java周期类

Java的Period类可以用来计算两个日子之间的区别。使用Period.between()方法可以确定两个日期之间的月、日、年的区别。上述策略的实践情况如下。

文件名:TimeDiff3.java

// Java code for the method described above

import java.time.*;
import java.util.*;

class TimeDiff3 {

    // method for printing the difference between
    // startdate and enddate
    static void
    findDifference(LocalDate startdate,
                   LocalDate enddate)
    {

        // finding the period between
        // the start date and end date
        Period difference
            = Period
                  .between(startdate,
                           enddate);

        // Printing the date difference
        // in terms of years, months, and days
        System.out.print(
            "Difference "
            + "between the two dates is: ");

        // Printing the result
        System.out.printf(
            "%d years, %d months"
                + " and %d days ",
            difference.getYears(),
            difference.getMonths(),
            difference.getDays());
    }

    // Main Code
    public static void main(String args[])
    {
        // Starting date
        LocalDate startdate
            = LocalDate.of(2017, 01, 10);

        // Ending date
        LocalDate enddate
            = LocalDate.of(2020, 06, 10);

        // Method Call
        findDifference(startdate,
                       enddate);
    }
}

输出

The difference between the two dates is: 3 years, 5 months, and 0 days

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程