Calculating days between two dates with Java

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

    // date format, it will be like "2015-01-01"
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    
    // convert a string to java.util.Date
    public static Date convertStringToJavaDate(String date)
            throws ParseException {
        DateFormat dataFormat = new SimpleDateFormat(DATE_FORMAT);
        return dataFormat.parse(date);
    }
    
    // plus days to a date
    public static Date plusJavaDays(Date date, int days) {
        // convert to jata-time
        DateTime fromDate = new DateTime(date);
        DateTime toDate = fromDate.plusDays(days);
        // convert back to java.util.Date
        return toDate.toDate();
    }
    
    // return a list of dates between the fromDate and toDate
    public static List getDatesBetween(Date fromDate, Date toDate) {
        List dates = new ArrayList(0);
        Date date = fromDate;
        while (date.before(toDate) || date.equals(toDate)) {
            dates.add(date);
            date = plusJavaDays(date, 1);
        }
        return dates;
    }
    

提交回复
热议问题