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)
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.
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.
| 归档时间: |
|
| 查看次数: |
51977 次 |
| 最近记录: |