Java Date getDate() deprecated, refactored to use calendar but looks ugly

Viewed 65958

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 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);
}
4 Answers

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.

Related