Java Date getDate() deprecated, refactored to use calendar but looks ugly
Eclipse is warning that I'm using a deprecated method:
eventDay = event.getEvent_s_date().getDate();
So I rewrote it as
eventDay = DateUtil.toCalendar(event.getEvent_s_date()).get(Calendar.DATE);
It seems to work but it looks ugly. My question is did I refactor this the best开发者_如何学Python way? If not, how would you refactor? I need the day number of a date stored in a bean.
I ended up adding a method in my DateUtils to clean it up
eventDay = DateUtil.getIntDate(event.getEvent_s_date());
public static int getIntDate(Date date) {
return DateUtil.toCalendar(date).get(Calendar.DATE);
}
It's fine. To me the uglier bit is the underscore in the method name. Java conventions frown upon underscores there.
You may want to take a look at joda-time. It is the de-facto standard for working with date/time:
new DateTime(date).getDayOfMonth();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Integer date = cal.get(Calendar.DATE);
/*Similarly you can get whatever value you want by passing value in cal.get()
ex DAY_OF_MONTH
DAY_OF_WEEK
HOUR_OF_DAY
etc etc..
*/
You can see java.util.Calendar API.
With Java 8 and later, it is pretty easy. There is LocalDate
class, which has getDayOfMonth()
method:
LocalDate date = now();
int dayOfMonth = date.getDayOfMonth();
With the java.time classes you do not need those third party libraries anymore. I would recommend reading about LocalDate
and LocalDateTime
.
If you want a more elegant Date/Time api, use Joda Time.
精彩评论