我想要一个Java程序来计算两个日期之间的天数。

输入第一个日期(德语表示法;有空格:"dd mm yyyy") 输入第二个日期。 程序应该计算两个日期之间的天数。

我怎样才能把闰年和夏天时包括进来呢?

我的代码:

import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class NewDateDifference {

    public static void main(String[] args) {

        System.out.print("Insert first date: ");
        Scanner s = new Scanner(System.in);
        String[] eingabe1 = new String[3];

        while (s.hasNext()) {
            int i = 0;
            insert1[i] = s.next();
            if (!s.hasNext()) {
                s.close();
                break;
            }
            i++;
        }

        System.out.print("Insert second date: ");
        Scanner t = new Scanner(System.in);
        String[] insert2 = new String[3];

        while (t.hasNext()) {
            int i = 0;
            insert2[i] = t.next();
            if (!t.hasNext()) {
                t.close();
                break;
            }
            i++;
        }

        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert1[0]));
        cal.set(Calendar.MONTH, Integer.parseInt(insert1[1]));
        cal.set(Calendar.YEAR, Integer.parseInt(insert1[2]));
        Date firstDate = cal.getTime();

        cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert2[0]));
        cal.set(Calendar.MONTH, Integer.parseInt(insert2[1]));
        cal.set(Calendar.YEAR, Integer.parseInt(insert2[2]));
        Date secondDate = cal.getTime();


        long diff = secondDate.getTime() - firstDate.getTime();

        System.out.println ("Days: " + diff / 1000 / 60 / 60 / 24);
    }
}

当前回答

想要得到只是天(没有时间),你可以使用ChronoUnit

ChronoUnit.DAYS.between(date1.toLocalDate(), date2.toLocalDate());

其他回答

在Java 8中,您可以通过使用LocalDate和DateTimeFormatter来实现这一点。从LocalDate的Javadoc:

LocalDate是一个表示日期的不可变日期时间对象, 通常被视为年-月-日。

可以使用DateTimeFormatter构造模式。下面是Javadoc,以及我使用的相关模式字符:

符号-含义-表示-示例 Y -年代-年份- 2004;04 M/L -月份-数字/文本- 7;07年;7月; 7月;J D——一个月的日期——数字——10

下面是例子:

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);
    }
}

最近的输入/输出示例:

23 01 1997
27 04 1997
Days between: 94

最近的第一个:

27 04 1997
23 01 1997
Days between: -94

你可以用更简单的方法来做:

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

当夏令时到来时,大多数/所有答案都给我们带来了问题。下面是我们针对所有日期的工作解决方案,不使用JodaTime。它利用日历对象:

public static int daysBetween(Calendar day1, Calendar day2){
    Calendar dayOne = (Calendar) day1.clone(),
            dayTwo = (Calendar) day2.clone();

    if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
        return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
    } else {
        if (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
            //swap them
            Calendar temp = dayOne;
            dayOne = dayTwo;
            dayTwo = temp;
        }
        int extraDays = 0;

        int dayOneOriginalYearDays = dayOne.get(Calendar.DAY_OF_YEAR);

        while (dayOne.get(Calendar.YEAR) > dayTwo.get(Calendar.YEAR)) {
            dayOne.add(Calendar.YEAR, -1);
            // getActualMaximum() important for leap years
            extraDays += dayOne.getActualMaximum(Calendar.DAY_OF_YEAR);
        }

        return extraDays - dayTwo.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ;
    }
}

最简单的方法:

public static long getDifferenceDays(Date d1, Date d2) {
    long diff = d2.getTime() - d1.getTime();
    return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
public class TestCode {

    public static void main(String[] args) {        
        String date1 = "23-04-2021";
        String date2 = "24-05-2021";
        System.out.println("NDays: " + nDays_Between_Dates(date1, date2));      
    }
    
    public static int nDays_Between_Dates(String date1, String date2) {
        int diffDays = 0;
        try {
            SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
            Date startDate = dates.parse(date1);
            Date endDate = dates.parse(date2);
            long diff = endDate.getTime() - startDate.getTime();
            diffDays = (int) (diff / (24 * 60 * 60 * 1000));            
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Math.abs(diffDays);
    }
}

nday: 31天

public static String dateCalculation(String getTime, String dependTime) {
    //Time A is getTime that need to calculate.
    //Time B is static time that Time A depend on B Time and calculate the result.

    Date date = new Date();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd H:mm:ss");
    Date dateObj = null;
    Date checkDate = null;

    try {
        dateObj = sdf.parse(getTime);
    } catch (ParseException e) {
        e.printStackTrace();
        return "0";
    }
    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    String checkInDate = dateFormat.format(dateObj).toString();
    Date defaultTime = null;
    try {
        defaultTime = dateFormat.parse(dependTime);
        checkDate = dateFormat.parse(checkInDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return "0";
    }

    try {
        if (dateFormat.parse(dateFormat.format(date)).after(defaultTime)) {
            long diff = checkDate.getTime() - defaultTime.getTime();
            Log.e("Difference", "onBindViewHolder: Difference: " + dateObj + " : " + defaultTime + " : " + diff);
            if (diff > 0) {
                long diffSeconds = diff / 1000 % 60;
                long diffMinutes = diff / (60 * 1000) % 60;
                long diffHours = diff / (60 * 60 * 1000);

                return "Late: " + diffHours + " Hour, " + diffMinutes + " Minutes, " + diffSeconds + " Sec";
            } else {
                return "0";
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
        return "0";
    }
    return "0";
}