我想要一个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);
    }
}

当前回答

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";
}
String dateStart = "01/14/2015 08:29:58";
String dateStop = "01/15/2015 11:31:48";

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1 = null;
Date d2 = null;

d1 = format.parse(dateStart);
d2 = format.parse(dateStop);

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

下面的方法非常适合我:

public int daysBetween(LocalDate later, LocalDate before) {
        SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
        int daysBetween = 0;
        try {
            Date dateBefore = myFormat.parse(localDateToString(before));
            Date dateAfter = myFormat.parse(localDateToString(later));
            long difference = dateAfter.getTime() - dateBefore.getTime();
            daysBetween = (int) (difference / (1000 * 60 * 60 * 24));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return daysBetween;
    }

    public String localDateToString(LocalDate date) {
        DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd MM yyyy");
        return date.format(myFormat).toString();
    }

Use:

public int getDifferenceDays(Date d1, Date d2) {
    int daysdiff = 0;
    long diff = d2.getTime() - d1.getTime();
    long diffDays = diff / (24 * 60 * 60 * 1000) + 1;
    daysdiff = (int) diffDays;
    return daysdiff;
}
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天