Calculating days between two dates with Java

前端 未结 11 1517
天命终不由人
天命终不由人 2020-11-22 04:42

I want a Java program that calculates days between two dates.

  1. Type the first date (German notation; with whitespaces: \"dd mm yyyy\")
  2. Type the second
11条回答
  •  别跟我提以往
    2020-11-22 05:17

    In Java 8, you could accomplish this by using LocalDate and DateTimeFormatter. From the Javadoc of LocalDate:

    LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day.

    And the pattern can be constructed using DateTimeFormatter. Here is the Javadoc, and the relevant pattern characters I used:

    Symbol - Meaning - Presentation - Examples

    y - year-of-era - year - 2004; 04

    M/L - month-of-year - number/text - 7; 07; Jul; July; J

    d - day-of-month - number - 10

    Here is the example:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    
    public class Java8DateExample {
        public static void main(String[] args) throws IOException {
            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
            final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            final String firstInput = reader.readLine();
            final String secondInput = reader.readLine();
            final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
            final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
            final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
            System.out.println("Days between: " + days);
        }
    }
    

    Example input/output with more recent last:

    23 01 1997
    27 04 1997
    Days between: 94
    

    With more recent first:

    27 04 1997
    23 01 1997
    Days between: -94
    

    Well, you could do it as a method in a simpler way:

    public static long betweenDates(Date firstDate, Date secondDate) throws IOException
    {
        return ChronoUnit.DAYS.between(firstDate.toInstant(), secondDate.toInstant());
    }
    

提交回复
热议问题