如何找到两个日期之间的天数?

发布于 2024-11-13 09:08:05 字数 742 浏览 2 评论 0原文

我有两个Date。我如何区分这两个日期之间的天数差异?

我听说过 SimpleDateFormat,但我不知道如何使用它。

我尝试过这个:

String fromdate = "Apr 10 2011";

SimpleDateFormat sdf;
sdf = new SimpleDateFormat("MMM DD YYYY"); 

sdf.parse(fromdate);

Calendar cal = Calendar.getInstance();
cal.setTime(sdf);

我也尝试过这个:

String date1 = "APR 11 2011";
String date2 = "JUN 02 2011";
String format = "MMM DD YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff / (24* 1000 * 60 * 60));
System.out.println(diffDays);

但我得到了异常“非法模式字符'Y'”。

I have two Dates. How can I tell the difference between these two dates in days?

I have heard of SimpleDateFormat, but I don't know how to use it.

I tried this:

String fromdate = "Apr 10 2011";

SimpleDateFormat sdf;
sdf = new SimpleDateFormat("MMM DD YYYY"); 

sdf.parse(fromdate);

Calendar cal = Calendar.getInstance();
cal.setTime(sdf);

I also tried this:

String date1 = "APR 11 2011";
String date2 = "JUN 02 2011";
String format = "MMM DD YYYY";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff / (24* 1000 * 60 * 60));
System.out.println(diffDays);

but I got the exception "Illegal pattern character 'Y'."

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

魂牵梦绕锁你心扉 2024-11-20 09:08:06

其他答案是正确的但已经过时了。

java.time

java.time框架内置于 Java 8 及更高版本中。这些类取代了旧的麻烦的日期时间类,例如 java.util.Date、.Calendar 和 & 。 java.text.SimpleDateFormatJoda-Time 团队还建议迁移到 java.time。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。

许多 java.time 功能都向后移植到 Java 6 和 Java 6。 ThreeTen-Backport 中的 7.0 版本,并在 ThreeTen-Backport 中进一步适应 Android。 com/JakeWharton/ThreeTenABP" rel="nofollow">ThreeTenABP。

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。

LocalDate

LocalDate 类表示仅日期值,没有时间和时区。

我建议尽可能为字符串使用标准 ISO 8601 格式。但在您的情况下,我们需要指定格式模式。

String input = "Apr 10 2011";

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu" );
LocalDate earlier = LocalDate.parse ( input , f );

DateTimeFormatter formatterOut = DateTimeFormatter.ofLocalizedDate ( FormatStyle.MEDIUM ).withLocale ( Locale.US );
String output = earlier.format ( formatterOut );

LocalDate later = earlier.plusDays ( 13 );

long days = ChronoUnit.DAYS.between ( earlier , later );

转储到控制台。

System.out.println ( "from earlier: " + earlier + " to later: " + later + " = days: " + days + " ending: " + output );

从早些时候:2011-04-10 到后来:2011-04-23 = 天:13 结束:2011 年 4 月 10 日

The other answers are correct but outdated.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

I suggest using standard ISO 8601 formats for your strings where possible. But in your case we need to specify a formatting pattern.

String input = "Apr 10 2011";

DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu" );
LocalDate earlier = LocalDate.parse ( input , f );

DateTimeFormatter formatterOut = DateTimeFormatter.ofLocalizedDate ( FormatStyle.MEDIUM ).withLocale ( Locale.US );
String output = earlier.format ( formatterOut );

LocalDate later = earlier.plusDays ( 13 );

long days = ChronoUnit.DAYS.between ( earlier , later );

Dump to console.

System.out.println ( "from earlier: " + earlier + " to later: " + later + " = days: " + days + " ending: " + output );

from earlier: 2011-04-10 to later: 2011-04-23 = days: 13 ending: Apr 10, 2011

巡山小妖精 2024-11-20 09:08:06

这里有一篇文章使用日历来解决这个问题。
http://tripoverit.blogspot.com/2007/07 /java-calculate-difference- Between-two.html

我相信Joda Time也为这种场景提供了API支持

Here is an article that uses Calendar to solve this problem.
http://tripoverit.blogspot.com/2007/07/java-calculate-difference-between-two.html

I believe that Joda Time also provides API support for this scenario

Spring初心 2024-11-20 09:08:06

你有两个 Date 对象?

答案再简单不过了。

public double computeDaysBetweenDates(Date d1, Date d2) {
    long diff;

    diff = d2.getTime() - d1.getTime();
    return ((double) diff) / (86400.0 * 1000.0);
}

日期对象是包含 UTC POSIX EPOCH 时间的 long 的薄包装,该时间是自 UTC 1970 年 1 月 1 日午夜以来经过的毫秒数。只需从较晚的值中减去较早的值即可获得间隔毫秒数。知道这一点后,您只需除以一天中的毫秒数即可。

请注意,这个答案假设一天是 86400 秒,并且......这基本上是正确的。

请注意,即使您已格式化日期字符串,此解决方案仍然适用。如果您能够首先将日期/时间解析为 Date 对象,那么您仍然可以使用它们调用此函数。

You have two Date objects?

The answer could not be simpler.

public double computeDaysBetweenDates(Date d1, Date d2) {
    long diff;

    diff = d2.getTime() - d1.getTime();
    return ((double) diff) / (86400.0 * 1000.0);
}

Date objects are thin wrappers around a long that contains a UTC POSIX EPOCH time, which is the number of milliseconds that have elapsed since midnight, Jan 1, 1970 UTC. You get your interval number of milliseconds just by subtracting the earlier value from the later. Knowing that, you just divide by the number of milliseconds in a day.

Note that this answer assumes that a day is 86400 seconds and ... that is mostly true.

Note that this solution is still apt even if you have formatted date strings. If you are able to parse your date/times into Date objects first, then you can still call this function with them.

笨死的猪 2024-11-20 09:08:06

这段代码应该告诉你如何做你需要的事情......

public static void main(String[] args) {
    Calendar firstOfTheMonthCalendar = Calendar.getInstance();
    firstOfTheMonthCalendar.set(Calendar.DAY_OF_MONTH, 1);

    Date firstOfTheMonthDate = firstOfTheMonthCalendar.getTime();
    Date nowDate = new Date();

    int diffInDays = determineDifferenceInDays(firstOfTheMonthDate, nowDate);
    System.out.println("Number of days betweens dates: " + diffInDays);
}

private static int determineDifferenceInDays(Date date1, Date date2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(date1);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(date2);
    long diffInMillis = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
    return (int) (diffInMillis / (24* 1000 * 60 * 60));
}

This code should show you how to do what you need...

public static void main(String[] args) {
    Calendar firstOfTheMonthCalendar = Calendar.getInstance();
    firstOfTheMonthCalendar.set(Calendar.DAY_OF_MONTH, 1);

    Date firstOfTheMonthDate = firstOfTheMonthCalendar.getTime();
    Date nowDate = new Date();

    int diffInDays = determineDifferenceInDays(firstOfTheMonthDate, nowDate);
    System.out.println("Number of days betweens dates: " + diffInDays);
}

private static int determineDifferenceInDays(Date date1, Date date2) {
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(date1);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(date2);
    long diffInMillis = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
    return (int) (diffInMillis / (24* 1000 * 60 * 60));
}
仅此而已 2024-11-20 09:08:06

java中两个日期字符串之间的差异

这将帮助您获得一些主意

Difference between two date strings in java

this will help you in getting some idea

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文