- You are correct in asking. You should not use the deprecated
parse(String!)
method. Not only was it deprecated for a reason, it is also confusing and likely to leave the reader of your code baffled about what’s going on.
- You should not convert from a date string in one format to a date string in a different format. In your program you should keep your date as a proper date object, not a string.
- The proper date object just mentioned should be taken from java.time, the modern Java date and time API. The
Date
class was poorly designed and is long outdated. It seems you were also using the SimpleDateFormat
class. It’s still worse, a notorious troublemaker of a class. Throw them away and use java.time instead.
java.time
I don’t know how your original string looked like. I am just taking an example string and showing you how to parse. In Java:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/u");
String originalDateString = "8/23/2020";
LocalDate yourDate = LocalDate.parse(originalDateString, dateFormatter);
System.out.println(yourDate);
Output:
2020-08-23
Do pick a class from java.time that picks up as much information from the string as possible. If your string included time of day, use LocalDateTime
instead of LocalDate
. If it also included time zone or offset from UTC, use ZonedDateTime
or OffsetDatetime
.
I consider it a sizeable advantage over your code that this code is explicit about which format is expected to be in the string.
When you need to give string output, format in this way:
DateTimeFormatter eDdMmmYyyy = DateTimeFormatter.ofPattern("E dd MMM yyyy", Locale.ENGLISH);
String formattedDate = yourDate.format(eDdMmmYyyy);
System.out.println(formattedDate);
Sun 23 Aug 2020
Date.parse() was magical in the bad way
I never knew what to expect from Date.parse()
. It was trying to be friendly and parse a lot of different formats, but which formats wasn’t well documented, and the behaviour of the method was extremely hard to predict. When I studied the documentation long enough, I was able to figure it out. But no one wants to study the documentation for a long time to understand one seemingly simple line of code.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links