Avión Avión - 3 days ago 5
Java Question

Normalizing spanish dates in Java

I need to parse spanish dates with the following format (which are strings):

6 junio 2012
20 mayo 2012


junio means june and mayo means may.

As you can see the month is written in spanish. How can I normalize it to get normalized dates (
yyyy-mm-dd
)?

In the example above I my desired output should be:

2012-06-06
2012-05-20


To be honest I dont know how to even start, searching a solution of this specific case is a bit hard.

Thanks in advance

Answer

Try the following code. The trick here is to initialize the SimpleDateFormat with both a language and country, in this case Spanish and Spain (España).

String yourDate = "20 mayo 2012";
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy", new Locale("es","ES"));
Date date = sdf.parse(yourDate);
System.out.println(date.toString());

Output:

Sun May 20 00:00:00 SGT 2012

If you want to format this Spanish date as yyyy-mm-dd you can again use the format() method from SimpleDateFormat:

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-mm-dd");
System.out.println(sdf2.format(date));
Comments