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);
}
Date are deprecated since Java 1.1, the class itself (and java. util. Calendar , too) are not officially deprecated, just declared as de facto legacy. The support of the old classes is still important for the goal of backwards compatibility with legacy code.
While the getYear method was deprecated 14 years before this question was asked, the entire Date class has later been replaced with java. time, the modern Java date and time API.
Both Date and Calendar are mutable, which tends to present issues when using either in an API.
In several fields, especially computing, deprecation is the discouragement of use of some terminology, feature, design, or practice, typically because it has been superseded or is no longer considered efficient or safe, without completely removing it or prohibiting its use.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With