不推荐使用Java Date getDate(),重构为使用日历但看起来很难看

jef*_*eff 22 java refactoring date

Eclipse警告我正在使用不推荐使用的方法:

eventDay = event.getEvent_s_date().getDate();
Run Code Online (Sandbox Code Playgroud)

所以我把它改写成了

eventDay = DateUtil.toCalendar(event.getEvent_s_date()).get(Calendar.DATE);
Run Code Online (Sandbox Code Playgroud)

它似乎工作,但它看起来很难看.我的问题是我是否以最好的方式重构了这个?如果没有,你会如何重构?我需要存储在bean中的日期的日期编号.

我最终在我的DateUtils中添加了一个方法来清理它

eventDay = DateUtil.getIntDate(event.getEvent_s_date());

public static int getIntDate(Date date) {
    return DateUtil.toCalendar(date).get(Calendar.DATE);
}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 28

没关系.对我来说,丑陋的位是方法名称中的下划线.Java约定在那里强调了下划线.

你可能想看看joda-time.它是处理日期/时间的事实上的标准:

new DateTime(date).getDayOfMonth();
Run Code Online (Sandbox Code Playgroud)

  • 我必须同意,re:方法名称中的下划线.这看起来像有人试图用Java重写一段PHP代码. (2认同)
  • @jeff你的数据库名称使用一个约定的事实并不意味着你的java代码不能使用另一个约定.实际上,这是一种常见的做法. (2认同)

Aru*_*ngh 19

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.. 
*/
Run Code Online (Sandbox Code Playgroud)

你可以看到java.util.Calendar API.


tor*_*ina 5

With Java 8 and later, it is pretty easy. There is LocalDate class, which has getDayOfMonth() method:

LocalDate date = now();
int dayOfMonth = date.getDayOfMonth();
Run Code Online (Sandbox Code Playgroud)

With the java.time classes you do not need those third party libraries anymore. I would recommend reading about LocalDate and LocalDateTime.