获取java中给出开始日期和结束日期时的天数、周数和年数
我是 Java 新手。我想要的是,当我将开始日期和结束日期作为参数传递给函数时,我想要获取开始日期和结束日期之间的天数、月数和年数。
I'm new to Java. What I want is when I pass the start date and the end date to a function as parameters I want to get the number of days, number of months and number of years between the start and the end date.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 JodaTime,则很简单:
If you use JodaTime, it's simple:
tl;dr
java.time
弗洛伊德的回答是正确的,但已经过时了。 Joda-Time 项目处于维护模式,其团队建议迁移到 java.time 类。
LocalDate
LocalDate
类表示没有时间和时区的日期。ChronoUnit
< code>ChronoUnit 类计算经过的时间。
Period
如果您希望将一个时间跨度分解为若干年和若干月和若干天,则使用
句点
班级。要获得方便的标准 ISO 8601 格式的字符串表示形式,请调用
toString.格式为
PnYnMnDTnHnMnS
,其中P
标记开始,T
分隔年-月-日和时-分-秒。所以一个半月就是P1M15D
。如果您希望每个部分都是数字,请调用 getter 方法。
关于 java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧日期时间类,例如 java.util.Date、.Calendar 和 & 。
java.text.SimpleDateFormat
。Joda-Time 项目,现已在 维护模式,建议迁移到 java.time。
要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。
许多 java.time 功能都向后移植到 Java 6 和 Java 6。 ThreeTen-Backport 中的 7 并进一步适应 Android 在 ThreeTenABP(请参阅如何使用...) 。
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如
Interval
、YearWeek
、YearQuarter
等。tl;dr
java.time
The Answer by Floyd is correct but outdated. The Joda-Time project is in maintenance mode, with its team advising migration to the java.time classes.
LocalDate
The
LocalDate
class represents a date without a time-of-day and without a time zone.ChronoUnit
The
ChronoUnit
class calculates elapsed time.Period
If you want one span of time broken out as a number of years and a number of months and a number of days, then use the
Period
class.To get the handy standard ISO 8601 formatted String representation, call
toString
. The format isPnYnMnDTnHnMnS
where theP
marks the beginning and theT
separates years-months-days from the hours-minutes-seconds. So a month and a half would beP1M15D
.If you want each part as a number, call getter methods.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as
java.util.Date
,.Calendar
, &java.text.SimpleDateFormat
.The Joda-Time project, now in maintenance mode, 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 (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.