Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 235
Morris Avatar asked Jun 29 '11 18:06

Morris


3 Answers

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.

like image 52
Jon Skeet Avatar answered Oct 17 '22 04:10

Jon Skeet


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.

like image 5
Bob Kuhar Avatar answered Oct 17 '22 04:10

Bob Kuhar


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

works for me.

like image 1
Prakash Nadar Avatar answered Oct 17 '22 04:10

Prakash Nadar