Reputation: 370
I use this function to parse strings into a date format
fun formatTimestampEDDMMMYYYY(date: String): String {
return E_DD_MMM_YYYY.format(Date.parse(date))
}
Whilst it works perfectly the gradle gives an error stating
'parse(String!): Long' is deprecated. Deprecated in Java
I've tried searching on google for an alternative, however many of the results for from pre 2015 and all suggest to do it the way I'm doing. If anyone has some up to date way of doing this I would keen to hear about it.
Upvotes: 0
Views: 1650
Reputation: 86323
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.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.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
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.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 2
Reputation: 1479
fun myFunction(formattedStr: String?): String {
formattedStr?.let {
val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
val outputFormat = SimpleDateFormat("EE, MMMM dd, yyyy h:mm a")
return outputFormat.format(inputFormat.parse(it))
}
return ""
}
You can try like above function. And change the date format for your requirement.
Upvotes: 0