Java中不推荐使用的Date方法?

The*_*boy 8 java deprecated simpledateformat parseexception

使用Java Date实用程序时的真正含义是什么并且已被弃用.这是否意味着不鼓励使用,还是暗示它被禁止?

我猜测使用弃用方法是不好的做法,但我不确定并想知道.

例如,我正在尝试使用如下代码

String date = request.getParameter("date"); 
model.setDate(new Date(date));
Run Code Online (Sandbox Code Playgroud)

当然......这是一个高级示例,但在这种情况下,我的模型使用Date类型,我需要将请求中的日期作为String拉出并使用它创建日期.

我的工作方式很好,但它使用的是不推荐使用的方法.

编辑 - 我已经回去使用了

SimpleDateFormat formatter = new SimpleDateFormat(); 
model.setDate(formatter.parse(request.getParameter("date");



日期的格式为MM/DD/YYY,如07/23/2010,但我收到了ParseException

这可能是什么?

And*_*yle 6

You're right that this is bad practice. In almost all cases, deprecated methods tell you what to use instead, and this is no exception (see the Javadocs).

You're trying to create a Date out of a String. But what format is the String in? How should it be parsed? Is it UK or US date format?

The "proper" way to do this is to create an instance of SimpleDateFormat, and call its parse() method passing in your text string. This is guaranteed to work in future, and will be more robust now.

  • ...或者最好使用更好的API,例如Joda Time :) (4认同)
  • @Jon Skeet,总是使用Better API的问题是你最终拥有一个API目录并不断检查存储库中的新版本. (2认同)
  • @The Elite Gentleman:虽然我同意你可以解决一般问题,但Joda Time稳定且*比现有的API好得多,它绝对值得做.它是java.util.Date/Calendar的一个*大规模*升级. (2认同)