简体   繁体   中英

How do you get the date/time range for “today” using the Joda date/time library in Java?

Assuming this is how you get the current time in Joda time :

DateTime now = new DateTime();

How do you calculate values for the variables dateTimeAtStartOfToday and dateTimeAtEndOfToday ?

What I'm trying to do is generate some SQL to do a lookup of all transactions that have occurred between the startOfToday and endOfToday .

I would use:

LocalDate today = now.toLocalDate();
LocalDate tomorrow = today.plusDays(1);

DateTime startOfToday = today.toDateTimeAtStartOfDay(now.getZone());
DateTime startOfTomorrow = tomorrow.toDateTimeAtStartOfDay(now.getZone());

Then check if startOfToday <= time < startOfTomorrow for any particular time.

Of course, it partly depends on exactly what's stored in the database - and what time zone you're interested in.

This works better, it turns out DateTime has a method called toInterval which does this exact thing (figures out midnight to midnight). In my tests, it appears to have no problem with DST transitions.

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 looks to be very well thought out.

if((sinceDate.getDayOfYear() == now.getDayOfYear())  && (sinceDate.year() == now.year()))
   //yep, do something today;

works for me.

As a Kotlin extension function it looks like this:

fun DateTime.isOnSameDay(timeOnDayToCheck: DateTime) =
  timeOnDayToCheck.toLocalDate().toInterval(this.zone).contains(this)

This does not contain times equaling the end of the day (start is included) so maybe add an "or"-case with 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));

This works...

DateTime dt = new DateTime();
DateMidnight dtStartDate = dt.toDateMidnight();
DateMidnight dtEndDate = dt.plusDays( 1 ).toDateMidnight();
System.out.println( dt + "\n" + dtStartDate + "\n" + dtEndDate );

...but as far as the SQL, I tend to use BETWEEN as the where clause rather than do the > and <= stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM