且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-29 19:41:24

其他答案正确但过时。

java .time 框架内置于Java 8及更高版本中。这些类代替旧的麻烦的日期时间类,例如 java.util.Date .Calendar ,& java.text.SimpleDateFormat Joda-Time 团队还建议迁移到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.

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

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

许多java.time功能都被后端移植到Java 6& 7在 ThreeTen-Backport 中,并进一步适应于 ThreeTenABP

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

ThreeTen-Extra 项目扩展了java.time和其他类。这个项目是未来可能添加到java.time的一个证明。

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.

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

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

转储到控制台。

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




从早期版本:2011-04-10至更高版本:2011-04 -23 =天:13结束日:2011年4月10日

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