Calculating days between two dates with Java

前端 未结 11 1512
天命终不由人
天命终不由人 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:02

    Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.

    Minimal working example:

    import java.util.Scanner;
    import org.joda.time.DateTime;
    import org.joda.time.Days;
    import org.joda.time.LocalDate;
    import org.joda.time.format.DateTimeFormat;
    import org.joda.time.format.DateTimeFormatter;
    
    public class DateTestCase {
    
        public static void main(String[] args) {
    
            System.out.print("Insert first date: ");
            Scanner s = new Scanner(System.in);
            String firstdate = s.nextLine();
            System.out.print("Insert second date: ");
            String seconddate = s.nextLine();
    
            // Formatter
            DateTimeFormatter dateStringFormat = DateTimeFormat
                    .forPattern("dd MM yyyy");
            DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
            DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
            int days = Days.daysBetween(new LocalDate(firstTime),
                                        new LocalDate(secondTime)).getDays();
            System.out.println("Days between the two dates " + days);
        }
    }
    

提交回复
热议问题