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

孤街浪徒 提交于 2019-12-11 14:38:56

问题


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

@Temporal(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.


回答1:


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...




回答2:


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.




回答3:


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();


来源:https://stackoverflow.com/questions/6611908/java-util-date-jodatime-given-a-java-util-date-generate-a-start-and-end-of-tha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!