我在Java 7中。
我对Joda-Time很新,想问一个简单的问题。如何在上周一凌晨2点到达日期?我的意思是:
____________________________________________________________________________
Week 1 | Week 2 |
______________________________________________________________|_____________|
MONDAY TUESDAY WENDSDAY THURSDAY FRIDAY SATURDAY SUNDAY| MONDAY ... |
2-00 a.m. | 2-00 a.m. |
______________________________________________________________|_____________|
所以,我需要在周一凌晨2点返回Week 1
。
iff 当前时间介于Week 1
周一凌晨2点到凌晨Week 2
周一2-00 a.m.
之间。
通过Joda-Time有没有一种相对简单的方法来实现这一目标?
答案 0 :(得分:3)
首先,Joda-Time的解决方案。第二,在Java 8及更高版本中内置的新java.time框架中的类似解决方案,旨在作为Joda-Time的继承者。请参阅Tutorial。
以下两种解决方案都遵循类似的逻辑,全面总结如下。 Joda DateTime和Java8 LocalDateTime使用fluent interface提供不可变的日期时间实现。要到上周一凌晨2点,您可以使用以下步骤使用流畅的界面链接后续呼叫:
DateTime currentTime = new DateTime();
DateTime dateResult;
boolean shouldReturnLastMonday = (currentTime.getDayOfWeek() != DateTimeConstants.MONDAY ||
currentTime.hourOfDay().get() < 2);
if (shouldReturnLastMonday) {
dateResult = currentTime.minus(Days.days(currentTime.getDayOfWeek() - DateTimeConstants.MONDAY))
.minus(currentTime.getMillisOfDay())
.plus(Hours.hours(2));
} else {
dateResult = currentTime.minus(currentTime.getMillisOfDay())
.plus(Hours.hours(2));
}
System.out.println(dateResult);
LocalDateTime currentTime = LocalDateTime.now();
LocalDateTime dateResult;
boolean shouldReturnLastMonday = (currentTime.getDayOfWeek() != DayOfWeek.MONDAY) ||
(currentTime.getDayOfWeek() != DayOfWeek.MONDAY && currentTime.getHour() < 2);
if(shouldReturnLastMonday) {
dateResult = currentTime.minus(currentTime.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue(), ChronoUnit.DAYS)
.minus(currentTime.getLong(ChronoField.MILLI_OF_DAY), ChronoUnit.MILLIS)
.plus(2, ChronoUnit.HOURS);
} else {
dateResult = currentTime.minus(currentTime.getLong(ChronoField.MILLI_OF_DAY), ChronoUnit.MILLIS)
.plus(2,ChronoUnit.HOURS);
}