https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Ayfri

12/02/2021, 3:45 PM
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

Kirill Grouchnikov

12/02/2021, 3:47 PM
image.png
You need to be more specific about the "doesn't work" part
a

Ayfri

12/02/2021, 3:49 PM
I'm using Kotlin 1.6.0 & JDK 17
r

Rob Elliot

12/02/2021, 3:51 PM
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

ribesg

12/02/2021, 3:52 PM
My guess also, maybe your default locale doesn’t know
May
a

Ayfri

12/02/2021, 3:52 PM
Ah yes maybe, I'm french so I sure have to modify the locale
yes it works thanks !
r

ribesg

12/02/2021, 3:54 PM
(But yeah use
java.time
, SimpleDateFormat is like 25 years old or something)
a

Ayfri

12/02/2021, 4:02 PM
Ah, what I have to use in
java.time
r

Rob Elliot

12/02/2021, 4:03 PM
Posted above
a

Ayfri

12/02/2021, 4:03 PM
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

Rob Elliot

12/02/2021, 4:07 PM
Just tested it - your pattern works fine with
May 15, 2009
r

ribesg

12/02/2021, 4:09 PM
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

Colton Idle

12/03/2021, 3:08 PM
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
3 Views