tmnd91
tmnd91

Reputation: 449

Cannot parse Date using SimpleDateFormat in java/scala

I have a date in this format:

"Fri Oct 31 15:07:24 2014" 

and I tried to parse it as I parsed a lot of other dates until now. I figured out his format is this one (consulting the Java docs (http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)):

"EEE MMM dd HH:mm:ss yyyy"

I tried from the scala REPL running this commands:

scala> import java.text.SimpleDateFormat
import java.text.SimpleDateFormat

scala> import java.util.Date
import java.util.Date

scala> val sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy")
sdf: java.text.SimpleDateFormat = java.text.SimpleDateFormat@2219f5ee

scala> sdf.parse("Fri Oct 31 15:07:24 2014")
java.text.ParseException: Unparseable date: "Fri Oct 31 15:07:24 2014"
  at java.text.DateFormat.parse(DateFormat.java:366)
  ... 33 elided

but as you can see I get a ParseException.

I tried removing the first part of the Date (and the pattern) like this:

"dd HH:mm:ss yyyy" -> "31 15:07:24 2014"

and all went fine, but when I try to add EEE or MMM I get the ParseException.

I also tried the pattern shown in the java docs that uses EEE and it fails too on my machine.

I've got Java 8 and scala 2.11.1

Thank you in advance.

Upvotes: 2

Views: 2805

Answers (1)

tmnd91
tmnd91

Reputation: 449

The problem was the Locale, by Default SimpleDateFormat takes the default Locale of the machine that's running, to set a different Locale (the "en" locale in this example) for the SimpleDateFormat you need to instantiate it this way:

new SimpleDateFormat(format,java.util.Locale.forLanguageTag("en"))

Upvotes: 3

Related Questions