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

当前回答

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

其他回答

更新: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));

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

Java日期库是出了名的坏。我建议使用Joda Time。它会为你照顾闰年、时区等。

最小工作示例:

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

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

最好的方法,它转换为一个字符串作为奖励;)

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        //Dates to compare
        String CurrentDate=  "09/24/2015";
        String FinalDate=  "09/26/2015";

        Date date1;
        Date date2;

        SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

        //Setting dates
        date1 = dates.parse(CurrentDate);
        date2 = dates.parse(FinalDate);

        //Comparing dates
        long difference = Math.abs(date1.getTime() - date2.getTime());
        long differenceDates = difference / (24 * 60 * 60 * 1000);

        //Convert long to String
        String dayDifference = Long.toString(differenceDates);

        Log.e("HERE","HERE: " + dayDifference);
    }
    catch (Exception exception) {
        Log.e("DIDN'T WORK", "exception " + exception);
    }
}
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";
}