Hi, I want to parse a simple date, and I don't kno...
# getting-started
a
Hi, I want to parse a simple date, and I don't know why this doesn't work
Copy code
val versionDate =  "May 5, 2009"
	val formattedDate = SimpleDateFormat("MMM d, yyyy").parse(versionDate)
	println(formattedDate)
What am I doing wrong ?
k
image.png
You need to be more specific about the "doesn't work" part
a
I'm using Kotlin 1.6.0 & JDK 17
r
Might be locale related? Different issue, but if possible use `DateTimeFormatter`:
Copy code
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale.ENGLISH

val versionDate =  "May 5, 2009"
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy", ENGLISH)
LocalDate.parse(versionDate, formatter)
SimpleDateFormat
is not threadsafe, which has bitten thousands of people who thought they could use it safely across threads. And
Date
(which is what it returns) & its companion
Calendar
are considered some of the worst designed classes of all time.
r
My guess also, maybe your default locale doesn’t know
May
a
Ah yes maybe, I'm french so I sure have to modify the locale
yes it works thanks !
r
(But yeah use
java.time
, SimpleDateFormat is like 25 years old or something)
a
Ah, what I have to use in
java.time
r
Posted above
a
Ah nice thanks !
Also, my date can have 5 or 15 for the day, do I have to really handle both cases depending on the date length or is there a pattern or something for this ?
r
Just tested it - your pattern works fine with
May 15, 2009
r
The doc clearly states it
Number: […] For parsing, the number of pattern letters is ignored unless it’s needed to separate two adjacent fields.
You would use
dd
if you wanted to format
5
to
05
, but for parsing there is no reason to use more than
d
c
im learning about dates more now and this was helpful. definitely need a rule that disallows using java.util date and calendar and any other "old" classes like formatters.
👍 1