Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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);
}
like image 932
jeff Avatar asked Oct 19 '10 20:10

jeff


People also ask

Is Java calendar deprecated?

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.

What can I use instead of getYear in Java?

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.

Is calendar immutable in Java?

Both Date and Calendar are mutable, which tends to present issues when using either in an API.

What does deprecated date mean?

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.


3 Answers

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();
like image 176
Bozho Avatar answered Sep 23 '22 06:09

Bozho


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.

like image 32
Arun Pratap Singh Avatar answered Sep 21 '22 06:09

Arun Pratap Singh


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.

like image 21
torina Avatar answered Sep 21 '22 06:09

torina