Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to date - roman month

I have following string: "05 X 02". How can i convert it to date? I don't want to convert it to string "05 10 02" and then to date. Is it possible?

Thanks for help.

So far i was trying use

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd M/L yy");

But it doesn't work. Also trying use DateTimeFormatterBuilder, but here I'm completely lost.

like image 316
Pulkownik Avatar asked Feb 19 '15 18:02

Pulkownik


1 Answers

You can change default format symbols to have romanic numbers for months

DateFormatSymbols symbols = DateFormatSymbols.getInstance();

final String[] romanMonths =  {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"};
symbols.setMonths(romanMonths);

SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yy", symbols);

System.out.println("My date " + formatter.parse("05 X 02"));

Here is a nice tutorial about how to have custom formatting symbols.

You can choose to change either short months via setShortMonths() or full months via setMonths()

UPDATE: Here is a version with DateTimeFormatterBuilder from JDK8

static final ImmutableMap<Long, String> ROMAN_MONTHS = ImmutableMap.<Long, String>builder()
                .put(1L, "I").put(2L, "II").put(3L, "III").put(4L, "IV").put(5L, "V")
                .put(6L, "VI").put(7L, "VII").put(8L, "VIII").put(9L, "IX").put(10L, "X")
                .put(11L, "XI").put(12L, "XII").build();

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NORMAL)
                    .appendLiteral(' ')
                    .appendText(ChronoField.MONTH_OF_YEAR, ROMAN_MONTHS)
                    .appendLiteral(' ')
                    .appendValue(ChronoField.YEAR, 4)
                    .toFormatter();

System.out.println("My date " + formatter.parse("5 X 2012"));
like image 134
vtor Avatar answered Sep 22 '22 05:09

vtor