Saturday, July 04, 2015

Transformation of String into Date respecting Locale

Let's say you need to parse a string into date and it is localized string (f.x. name of month on local language). In past I would definitely define an array with months and then parse a String to get a number of my month and then build a Date object. In Java it's pretty simple (almost 1 line of code).

Locale approach

package parser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class parser {

 public static void main(String[] args) throws ParseException {
  Locale locale = new Locale("ru");
  Date date = convertStringToDate("19 Сентября 2004", "d MMMM yyyy", locale);
  System.out.println(date); // Sun Sep 19 00:00:00 CEST 2004
 }
 
 public static java.util.Date convertStringToDate(String dateString, String format, Locale locale) throws ParseException {
  return new SimpleDateFormat("d MMMM yyyy", locale).parse(dateString);
 }
}
Alternatively, if you need to define months yourself use DateFormatSymbols

Define symbols in DateFormatSymbols

package parser;

import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class parser {

 public static void main(String[] args) throws ParseException {
  String months[] = {"Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"};
  DateFormatSymbols dfs = new DateFormatSymbols();
  dfs.setMonths(months);
  
  SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy");
  sdf.setDateFormatSymbols(dfs);
  System.out.print(sdf.parse("19 Сентября 2004")); // Sun Sep 19 00:00:00 CEST 2004
 }
}

No comments :