用Java计算两个日期之间的天数 [英] Calculating days between two dates with Java

查看:38
本文介绍了用Java计算两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want a Java program that calculates days between two dates.

  1. 输入第一个日期(德语符号;带空格:dd mm yyyy")
  2. 输入第二个日期.
  3. 程序应该计算两个日期之间的天数.

如何包含闰年和夏令时?

How can I include leap years and summertime?

我的代码:

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

推荐答案

更新: 2013 年的原始答案现已过时,因为某些类已被替换.执行此操作的新方法是使用新的 java.time 类.

UPDATE: The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time classes.

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 小时天数,而不是日历天数.对于后者,使用

Note that this solution will give the number of actual 24 hour-days, not the number of calendar days. For the latter, use

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

<小时>

原始答案(自 Java 8 起已过时)


Original answer (outdated as of Java 8)

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

You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat class for it - try this:

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 也可以手动转换:

Since there have been some discussions regarding the correctness of this code: it does indeed take care of leap years. However, the TimeUnit.DAYS.convert function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff can also be converted by hand:

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

请注意,这是一个 float 值,不一定是 int.

Note that this is a float value, not necessarily an int.

这篇关于用Java计算两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆