📌  相关文章
📜  在Java查找两个日期之间差异的持续时间

📅  最后修改于: 2021-09-05 08:45:34             🧑  作者: Mango

给定两个日期start_dateend_date以及字符串形式的时间,任务是在Java找出两个日期之间的差异。

例子:

方法 1:使用 SimpleDateFormat 和 Date 类查找两个日期之间的差异。以下是步骤:

  1. 创建 SimpleDateFormat 类的对象并将字符串格式转换为日期对象。
  2. 从字符串解析 start_date 和 end_date 以生成日期,这可以通过使用 simpleDateFormat 类的 parse() 方法来完成。
  3. 使用Java的getTime() 方法作为d2.getTime() – d1.getTime()查找两个日期之间的时差(以毫秒为单位)
  4. 使用日期时间数学公式找出两个日期之间的差异。它返回两个指定日期之间的年、日、小时、分钟和秒。
  5. 打印最终结果。

下面是上述方法的实现:

Java
// Java program for the above approach
  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
  
class GFG {
  
    // Function to print difference in
    // time start_date and end_date
    static void
    findDifference(String start_date,
                   String end_date)
    {
  
        // SimpleDateFormat converts the
        // string format to date object
        SimpleDateFormat sdf
            = new SimpleDateFormat(
                "dd-MM-yyyy HH:mm:ss");
  
        // Try Block
        try {
  
            // parse method is used to parse
            // the text from a string to
            // produce the date
            Date d1 = sdf.parse(start_date);
            Date d2 = sdf.parse(end_date);
  
            // Calucalte time difference
            // in milliseconds
            long difference_In_Time
                = d2.getTime() - d1.getTime();
  
            // Calucalte time difference in
            // seconds, minutes, hours, years,
            // and days
            long difference_In_Seconds
                = (difference_In_Time
                   / 1000)
                  % 60;
  
            long difference_In_Minutes
                = (difference_In_Time
                   / (1000 * 60))
                  % 60;
  
            long difference_In_Hours
                = (difference_In_Time
                   / (1000 * 60 * 60))
                  % 24;
  
            long difference_In_Years
                = (difference_In_Time
                   / (1000l * 60 * 60 * 24 * 365));
  
            long difference_In_Days
                = (difference_In_Time
                   / (1000 * 60 * 60 * 24))
                  % 365;
  
            // Print the date difference in
            // years, in days, in hours, in
            // minutes, and in seconds
  
            System.out.print(
                "Difference "
                + "between two dates is: ");
  
            System.out.println(
                difference_In_Years
                + " years, "
                + difference_In_Days
                + " days, "
                + difference_In_Hours
                + " hours, "
                + difference_In_Minutes
                + " minutes, "
                + difference_In_Seconds
                + " seconds");
        }
  
        // Catch the Exception
        catch (ParseException e) {
            e.printStackTrace();
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given start Date
        String start_date
            = "10-01-2018 01:10:20";
  
        // Given end Date
        String end_date
            = "10-06-2020 06:30:50";
  
        // Function Call
        findDifference(start_date, end_date);
    }
}


Java
// Java program to find the
// difference between two dates
  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.Date;
  
class GFG {
  
    // Function to print difference in
    // time start_date and end_date
    static void findDifference(String start_date,
                               String end_date)
    {
        // SimpleDateFormat converts the
        // string format to date object
        SimpleDateFormat sdf
            = new SimpleDateFormat(
                "dd-MM-yyyy HH:mm:ss");
  
        // Try Class
        try {
  
            // parse method is used to parse
            // the text from a string to
            // produce the date
            Date d1 = sdf.parse(start_date);
            Date d2 = sdf.parse(end_date);
  
            // Calucalte time difference
            // in milliseconds
            long difference_In_Time
                = d2.getTime() - d1.getTime();
  
            // Calucalte time difference in seconds,
            // minutes, hours, years, and days
            long difference_In_Seconds
                = TimeUnit.MILLISECONDS
                      .toSeconds(difference_In_Time)
                  % 60;
  
            long difference_In_Minutes
                = TimeUnit
                      .MILLISECONDS
                      .toMinutes(difference_In_Time)
                  % 60;
  
            long difference_In_Hours
                = TimeUnit
                      .MILLISECONDS
                      .toHours(difference_In_Time)
                  % 24;
  
            long difference_In_Days
                = TimeUnit
                      .MILLISECONDS
                      .toDays(difference_In_Time)
                  % 365;
  
            long difference_In_Years
                = TimeUnit
                      .MILLISECONDS
                      .toDays(difference_In_Time)
                  / 365l;
  
            // Print the date difference in
            // years, in days, in hours, in
            // minutes, and in seconds
            System.out.print(
                "Difference"
                + " between two dates is: ");
  
            // Print result
            System.out.println(
                difference_In_Years
                + " years, "
                + difference_In_Days
                + " days, "
                + difference_In_Hours
                + " hours, "
                + difference_In_Minutes
                + " minutes, "
                + difference_In_Seconds
                + " seconds");
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given start_date
        String start_date
            = "10-01-2018 01:10:20";
  
        // Given end_date
        String end_date
            = "10-06-2020 06:30:50";
  
        // Function Call
        findDifference(start_date,
                       end_date);
    }
}


Java
// Java program for the above approach
  
import java.time.*;
import java.util.*;
  
class GFG {
  
    // Function to print difference in
    // time start_date and end_date
    static void
    findDifference(LocalDate start_date,
                   LocalDate end_date)
    {
  
        // find the period between
        // the start and end date
        Period diff
            = Period
                  .between(start_date,
                           end_date);
  
        // Print the date difference
        // in years, months, and days
        System.out.print(
            "Difference "
            + "between two dates is: ");
  
        // Print the result
        System.out.printf(
            "%d years, %d months"
                + " and %d days ",
            diff.getYears(),
            diff.getMonths(),
            diff.getDays());
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Start date
        LocalDate start_date
            = LocalDate.of(2018, 01, 10);
  
        // End date
        LocalDate end_date
            = LocalDate.of(2020, 06, 10);
  
        // Function Call
        findDifference(start_date,
                       end_date);
    }
}


输出:

方法二:使用Java内置类TimeUnit可以更好的找出两个日期的差异。

下面是上述方法的实现:

Java

// Java program to find the
// difference between two dates
  
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.Date;
  
class GFG {
  
    // Function to print difference in
    // time start_date and end_date
    static void findDifference(String start_date,
                               String end_date)
    {
        // SimpleDateFormat converts the
        // string format to date object
        SimpleDateFormat sdf
            = new SimpleDateFormat(
                "dd-MM-yyyy HH:mm:ss");
  
        // Try Class
        try {
  
            // parse method is used to parse
            // the text from a string to
            // produce the date
            Date d1 = sdf.parse(start_date);
            Date d2 = sdf.parse(end_date);
  
            // Calucalte time difference
            // in milliseconds
            long difference_In_Time
                = d2.getTime() - d1.getTime();
  
            // Calucalte time difference in seconds,
            // minutes, hours, years, and days
            long difference_In_Seconds
                = TimeUnit.MILLISECONDS
                      .toSeconds(difference_In_Time)
                  % 60;
  
            long difference_In_Minutes
                = TimeUnit
                      .MILLISECONDS
                      .toMinutes(difference_In_Time)
                  % 60;
  
            long difference_In_Hours
                = TimeUnit
                      .MILLISECONDS
                      .toHours(difference_In_Time)
                  % 24;
  
            long difference_In_Days
                = TimeUnit
                      .MILLISECONDS
                      .toDays(difference_In_Time)
                  % 365;
  
            long difference_In_Years
                = TimeUnit
                      .MILLISECONDS
                      .toDays(difference_In_Time)
                  / 365l;
  
            // Print the date difference in
            // years, in days, in hours, in
            // minutes, and in seconds
            System.out.print(
                "Difference"
                + " between two dates is: ");
  
            // Print result
            System.out.println(
                difference_In_Years
                + " years, "
                + difference_In_Days
                + " days, "
                + difference_In_Hours
                + " hours, "
                + difference_In_Minutes
                + " minutes, "
                + difference_In_Seconds
                + " seconds");
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given start_date
        String start_date
            = "10-01-2018 01:10:20";
  
        // Given end_date
        String end_date
            = "10-06-2020 06:30:50";
  
        // Function Call
        findDifference(start_date,
                       end_date);
    }
}
输出:

方法 3:使用Java的Period 类来查找两天之间的差异。 Period.between() 方法用于计算两个日期之间的年、月和日差异。

下面是上述方法的实现:

Java

// Java program for the above approach
  
import java.time.*;
import java.util.*;
  
class GFG {
  
    // Function to print difference in
    // time start_date and end_date
    static void
    findDifference(LocalDate start_date,
                   LocalDate end_date)
    {
  
        // find the period between
        // the start and end date
        Period diff
            = Period
                  .between(start_date,
                           end_date);
  
        // Print the date difference
        // in years, months, and days
        System.out.print(
            "Difference "
            + "between two dates is: ");
  
        // Print the result
        System.out.printf(
            "%d years, %d months"
                + " and %d days ",
            diff.getYears(),
            diff.getMonths(),
            diff.getDays());
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Start date
        LocalDate start_date
            = LocalDate.of(2018, 01, 10);
  
        // End date
        LocalDate end_date
            = LocalDate.of(2020, 06, 10);
  
        // Function Call
        findDifference(start_date,
                       end_date);
    }
}
输出:

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live