A non-deprecated exact equivalent of Date(String s) in Java?

Here's my guess (I posted as community wiki so you can vote up if I'm right):

Date parsed;
try {
    SimpleDateFormat format =
        new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    parsed = format.parse(dateString);
}
catch(ParseException pe) {
    throw new IllegalArgumentException(pe);
}

SimpleDateFormat is the way to go. Can I point out, however, that you may feel compelled to define one SimpleDateFormat instance and build Date objects using this. If you do, beware that SimpleDateFormat is not thread-safe and you may be exposing yourself to some potentially hard-to-debug issues!

I'd recommend taking this opportunity to look at Joda which is a much better thought-out (and thread-safe) API. It forms the basis of JSR-310, which is the new proposed Java Date API.

I understand this is a bit more work. However it's probably worthwhile given that you're having to refactor code at the moment.


If you take a look at source of the Date.parse(String s) method that Nicolas mentions, you'll see that it will be difficult or impossible to construct a date format that exactly reproduces the behavior.

If you just want to eliminate the warning, you could put @SuppressWarnings({“deprecation”}) outside the method calling the Date(String) constructor.

If you really want to ensure future access to this behavior with future JREs, you might be able to just extract the method from the JDK sources and put it into your own sources. This would require a careful read of the source code licenses and consideration of their application to your specific project, and might not be permissible at all.

Tags:

Java

Date