开发者

java.util.Date/JodaTime: Given a java.util.Date, generate a start and end of that given date

开发者 https://www.devze.com 2023-03-18 21:18 出处:网络
If I was to given a specific java.util.Date, how can I generate a start and end of that given date. For example, I my date is August 25, 2011, then my start date would be August 25, 2011 00 00 00 and

If I was to given a specific java.util.Date, how can I generate a start and end of that given date. For example, I my date is August 25, 2011, then my start date would be August 25, 2011 00 00 00 and my end of date would be August 25, 2011 23 59 59

Background: (Read below if you want to know why I ask this question)

I use JPA to map date to my MySql database like this. I want the date to have time as well, so I use TemoporalType.TIMESTAMP

@Te开发者_如何学编程mporal(TemporalType.TIMESTAMP)
private Date dateProcess; //java.util.Date

I need to query all data given a specific date, and since date is stored as above, I need a date range to achieve what I want.

My game plan is to convert java.util.Date to JodaTime#DateTinme, then construct the start and end date there, and convert it back so that I can pass as parameters to JPQL. But it seems that JodaTime is very immutable, I cant seem to see a setter method any where.


A java.util.Date represents an instant in time, with no reference to a time zone or calendar. The same instant will have a very different start/end of day depending on the time zone of the observer.

You could do something like:

DateTime dateTime = new DateTime(date.getTime(), timeZone);
LocalDate localDate = dateTime.ToLocalDate();

DateTime startOfDay = localDate.toDateTimeAtStartOfDay(timeZone);
DateTime startOfNextDay = localDate.plusDays(1).toDateTimeAtStartOfDay(timeZone);

From the last two variables, you can get back to java.util.Date values if you want. Usually they'll both be midnight, but they might not be.

Note that you should use the start of the next day in an exclusive way, rather than the last second of the current day in an inclusive way, in order to avoid missing values such as August 25, 2011 23:59:59.500...


I believe the type you want is DateMidnight. Make a new DateMidnight and pass it the DateTime in question, and it will take the date at midnight in the morning of the same day. You could then also use the plusDays() function to add 1 day to get your end time.


Date date; // your date

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date startDate = calendar.getTime();

calendar.set(Calendar.HOUR, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
Date endDate = calendar.getTime();
0

精彩评论

暂无评论...
验证码 换一张
取 消