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

其他回答

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

更新:2013年的原始答案现在已经过时,因为一些类已经被替换了。新的方法是使用新的java。时间类。

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    LocalDateTime date1 = LocalDate.parse(inputString1, dtf);
    LocalDateTime date2 = LocalDate.parse(inputString2, dtf);
    long daysBetween = Duration.between(date1, date2).toDays();
    System.out.println ("Days: " + daysBetween);
} catch (ParseException e) {
    e.printStackTrace();
}

注意,这个解决方案给出的是实际的24小时天数,而不是日历天数。对于后者,请使用

long daysBetween = ChronoUnit.DAYS.between(date1, date2)

原始答案(Java 8已过时)

您正在使用字符串进行一些不必要的转换。有一个SimpleDateFormat类-试试这个:

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

编辑:由于有一些关于这段代码正确性的讨论:它确实考虑到了闰年。然而,TimeUnit.DAYS.convert函数失去了精度,因为毫秒被转换为天(更多信息请参阅链接文档)。如果这是一个问题,diff也可以手动转换:

float days = (diff / (1000*60*60*24));

注意,这是一个浮点值,不一定是整型。

我们可以利用LocalDate和ChronoUnit java库,下面的代码工作正常。 Date的格式为yyyy-MM-dd。

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
class Solution {
    public int daysBetweenDates(String date1, String date2) {
        LocalDate dt1 = LocalDate.parse(date1);
        LocalDate dt2= LocalDate.parse(date2);

        long diffDays = ChronoUnit.DAYS.between(dt1, dt2);

        return Math.abs((int)diffDays);
    }
}
// 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<Date> getDatesBetween(Date fromDate, Date toDate) {
    List<Date> dates = new ArrayList<Date>(0);
    Date date = fromDate;
    while (date.before(toDate) || date.equals(toDate)) {
        dates.add(date);
        date = plusJavaDays(date, 1);
    }
    return dates;
}
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.");