![](/img/trans.png)
[英]How do you get the date/time range for “this week” using the Joda date/time library in Java?
[英]How do you get the date/time range for “today” using the Joda date/time library in Java?
我會用:
LocalDate today = now.toLocalDate();
LocalDate tomorrow = today.plusDays(1);
DateTime startOfToday = today.toDateTimeAtStartOfDay(now.getZone());
DateTime startOfTomorrow = tomorrow.toDateTimeAtStartOfDay(now.getZone());
然后檢查startOfToday <= time < startOfTomorrow
是否在任何特定時間。
當然,它部分取決於數據庫中存儲的內容 - 以及您感興趣的時區。
這樣做效果更好,事實證明DateTime有一個名為toInterval的方法可以做到這一點(從午夜到午夜計算)。 在我的測試中,它似乎沒有DST過渡的問題。
DateTime now = new DateTime();
DateTime startOfToday = now.toDateMidnight().toInterval().getStart();
DateTime endOfToday = now.toDateMidnight().toInterval().getEnd();
System.out.println( "\n" + now + "\n" + startOfToday + "\n" + endOfToday + "\n" );
JODA看起來非常深思熟慮。
if((sinceDate.getDayOfYear() == now.getDayOfYear()) && (sinceDate.year() == now.year()))
//yep, do something today;
適合我。
作為Kotlin擴展函數,它看起來像這樣:
fun DateTime.isOnSameDay(timeOnDayToCheck: DateTime) =
timeOnDayToCheck.toLocalDate().toInterval(this.zone).contains(this)
這不包含等於當天結束的時間(包含開頭),因此可以使用interval.getEnd().isEqual(this))
添加“或” - 大小寫。
import org.joda.time.DateTime;
import org.joda.time.DateTimeMidnight;
DateTime dateTimeAtStartOfToday = new DateTime(new DateTimeMidnight());
DateTime dateTimeAtEndOfToday = new DateTime((new DateTimeMidnight()).plusDays(1));
這有效......
DateTime dt = new DateTime();
DateMidnight dtStartDate = dt.toDateMidnight();
DateMidnight dtEndDate = dt.plusDays( 1 ).toDateMidnight();
System.out.println( dt + "\n" + dtStartDate + "\n" + dtEndDate );
...但就SQL而言,我傾向於使用BETWEEN作為where子句,而不是使用>和<= stuff
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.