Java Date getDate() 已弃用,重构为使用日历但看起来很丑
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3972568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Date getDate() deprecated, refactored to use calendar but looks ugly
提问by jeff
Eclipse is warning that I'm using a deprecated method:
Eclipse 警告我正在使用不推荐使用的方法:
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.
它似乎有效,但看起来很难看。我的问题是我是否以最好的方式重构了这个?如果没有,你将如何重构?我需要存储在 bean 中的日期的天数。
I ended up adding a method in my DateUtils to clean it up
我最终在我的 DateUtils 中添加了一个方法来清理它
eventDay = DateUtil.getIntDate(event.getEvent_s_date());
eventDay = DateUtil.getIntDate(event.getEvent_s_date());
public static int getIntDate(Date date) {
return DateUtil.toCalendar(date).get(Calendar.DATE);
}
采纳答案by Bozho
It's fine. To me the uglier bit is the underscore in the method name. Java conventions frown upon underscores there.
没关系。对我来说,更难看的是方法名称中的下划线。Java 约定不赞成那里的下划线。
You may want to take a look at joda-time. It is the de-facto standard for working with date/time:
您可能想看看joda-time。它是处理日期/时间的事实上的标准:
new DateTime(date).getDayOfMonth();
回答by highlycaffeinated
回答by Arun Pratap Singh
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.
你可以看到java.util.Calendar API。
回答by torina
With Java 8 and later, it is pretty easy. There is LocalDate
class, which has getDayOfMonth()
method:
使用 Java 8 及更高版本,这很容易。有一个LocalDate
类,它有getDayOfMonth()
方法:
LocalDate date = now();
int dayOfMonth = date.getDayOfMonth();
With the java.timeclasses you do not need those third party libraries anymore. I would recommend reading about LocalDate
and LocalDateTime
.
使用java.time类,您不再需要那些第三方库。我建议阅读关于LocalDate
和LocalDateTime
。