[英]JodaTime - Number of days in each months between 2 dates
我有2个这样的日期:
DateTime startingDate = new DateTime(STARTING_YEAR, STARTING_MONTH, STARTING_DAY, 0, 0);
DateTime endingDate = new DateTime(ENDING_YEAR, ENDING_MONTH, ENDING_DAY, 0, 0);
TOTAL_DAYS = Days.daysBetween(startingDate, endingDate).getDays();
很容易知道两天之间的总天数,但是我对API一点都不熟悉,并且想知道是否有一种更简单的方法来查找两个日期之间没有循环和if的每个月中的天数。
范例:
DateTime startingDate = new DateTime(2000, 1, 1, 0, 0);
DateTime endingDate = new DateTime(2000, 2, 3, 0, 0);
一月份为31,二月份为2。
谢谢!
我终于做了一个循环。
DateTime startingDate = new DateTime(STARTING_YEAR, STARTING_MONTH, STARTING_DAY, 0, 0);
DateTime endingDate = new DateTime(ENDING_YEAR, ENDING_MONTH, ENDING_DAY, 0, 0);
TOTAL_DAYS = Days.daysBetween(startingDate, endingDate).getDays();
DateTime currentDate = startingDate;
System.out.println(currentDate.dayOfMonth().getMaximumValue() - currentDate.dayOfMonth().get() + 1);
currentDate = currentDate.plus(Period.months(1));
while (currentDate.isBefore(endingDate)) {
System.out.println(currentDate.dayOfMonth().getMaximumValue());
currentDate = currentDate.plus(Period.months(1));
}
System.out.println(endingDate.dayOfMonth().get());
双天=(endingDate.getMillis()-startingDate.getMillis())/ 86400000.0;
将天数作为浮点数。 如果只希望整天数,请截断。
这可能会有所帮助:
DateTime startingDate = new DateTime(2000, 1, 1, 0, 0);
DateTime endingDate = new DateTime(2000, 2, 3, 0, 0);
Duration duration = new Duration(startingDate, endingDate);
System.out.println(duration.getStandardDays());//get the difference in number of days
FYI是Joda-Time项目,目前处于维护模式 ,建议迁移到java.time。
如果要单独处理每个中间月份,则需要进行迭代。 但是,该工作在YearMonth
类中有所简化。 此外,您可以使用Streams掩盖迭代。
java.time类明智地使用Half-Open方法来定义时间跨度。 这意味着,一开始是包容性的 ,而结局是排他的 。 因此月份范围需要结束与月结束目标月以下 。
TemporalAdjuster
TemporalAdjuster
接口提供对日期时间值的操纵。 TemporalAdjusters
类(注意s
)提供了一些方便的实现。 这里我们需要:
LocalDate
LocalDate
类表示没有日期和时区的仅日期值。
LocalDate startDate = LocalDate.of( 2000 , 1 , 1 );
YearMonth ymStart = YearMonth.from( startDate );
LocalDate stopDate = LocalDate.of( 2000 , 2 , 3 );
LocalDate stopDateNextMonth = stopDate.with( TemporalAdjusters.firstDayOfNextMonth() );
YearMonth ymStop = YearMonth.from( stopDateNextMonth );
每月循环一次。
顺便说一下,您可以通过Month
枚举对象要求Month
的本地化名称。
YearMonth ym = ymStart;
do {
int daysInMonth = ym.lengthOfMonth ();
String monthName = ym.getMonth ().getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH );
System.out.println ( ym + " : " + daysInMonth + " jours en " + monthName );
// Prepare for next loop.
ym = ym.plusMonths ( 1 );
} while ( ym.isBefore ( ymStop ) );
2000年1月:31 jours en janvier
2000-02:29周日
java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧式旧式日期时间类,例如java.util.Date
, .Calendar
和java.text.SimpleDateFormat
。
现在处于维护模式的Joda-Time项目建议迁移到java.time。
要了解更多信息,请参见Oracle教程 。 并在Stack Overflow中搜索许多示例和说明。 规格为JSR 310 。
在哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。 该项目为将来可能在java.time中添加内容提供了一个试验场。 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.