Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Date.parse() in Java safe to use, even though it is deprecated? If not, is there a viable alternative? [closed]

I often use Date.parse(String) to parse a date in an unknown format. It seems to work fine for my use cases so far, but I'm wondering why it was deprecated, and whether I should avoid it? The docs just say:

As of JDK version 1.1, replaced by DateFormat.parse(String s)

However, there's no static parse method in DateFormat, just an instance method, which requires a DateFormat object, which I won't have for an unknown date format.

So, I'm wondering...

  • Is there any official statement somewhere from the Java designers about why they chose to deprecate it?
  • If this method works fine for my use cases so far, can I rely on this functionality being available in future versions of Java?
  • Is there a viable alternative that is not deprecated for parsing a string that is in one of many possible common date formats?
like image 506
Robert Fraser Avatar asked Feb 07 '23 00:02

Robert Fraser


2 Answers

Date.parse(String) was deprecated because it doesn't internationalize well. SimpleDateFormat or Calendar objects are preferred.

For personal uses where you know it parses dates well, you probably don't need to avoid it, but you should probably get in the habit of using the more standard options if you're going to be writing more serious date-sensitive code.

like image 102
K. Akyoobd Avatar answered Feb 09 '23 14:02

K. Akyoobd


The simplest way now to parse a Date is to use SimpleDateFormat, but you need to create an instance first there is no static method anymore.

SimpleDateFormat format = new SimpleDateFormat(pattern);
Date date = format.parse(strDate)

Date and Calendar are simply badly written because they are confusing and error prone, they are meant to totally be replaced by the version of joda time that has been included into Java 8, so in anyway you should rely on this method anymore as it will simply be removed very soon.

So if you use Java 8, I highly encourage you to use directly DateTimeFormat, if you have a previous version, you should use SimpleDateFormat as mentioned above.

What you need to do is:

  1. To list all the patterns that you need to support in your code
  2. Put them into a collection or an array
  3. Then test each of them until the method parse(String) doesn't raise a ParseException, something like this
like image 36
Nicolas Filotto Avatar answered Feb 09 '23 12:02

Nicolas Filotto