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

Morris picture Morris · Jun 29, 2011 · Viewed 27k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Jun 29, 2011

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.