I'm replacing a placeholder in my Word template with a date range like this
//...getting from and to dates
String format = "%1$-3tb %1$tY - %2$-3tb %2$tY";
dateString = String.format(format, from, to);
//...retrieving the Text object...
textElement.setValue(dateString);
The console output looks nice:
Nov 2016 - Nov 2016
Jan 2016 - Jan 2016
Jul 2012 - Mär 2005
Two questions:
The easy answer to the side question is: upgrade to Java 9 or later.
YearMonth from = YearMonth.of(2012, Month.MAY);
YearMonth to = YearMonth.of(2013, Month.NOVEMBER);
String format = "%1$-3tb %1$tY - %2$-3tb %2$tY";
String dateString = String.format(Locale.GERMAN, format, from, to);
System.out.println(dateString);
Mai 2012 - Nov. 2013
Java gets its locale data — including the month abbreviations used in different languages — from up to four sources. Up to and including Java 8 the default was Java’s own, but at least in Java 8 Unicode’s Common Locale Data Repository, CLDR, are distributed with Java too (not sure about Java 7). From Java 9 CLDR data are the default, but Java’s own are avaiable as COMPAT. The system property java.locale.providers
controls which locale data to use. So I had expected that setting this property to CLDR
or CLDR,JRE
would work on Java 8, but on my Java 8 it doesn’t, Seems CLDR data are not the same in both Java versions.
In any case, while Java’s own German month abbreviations are without dots, in CLDR German month abbreviations in Java 9 are with dot. Month names up to four letters (Mai, Juni and Juli) are written in full without dot.
Java 8 answer to the side question: java.time, the modern Java date and time API allows us to define our own texts. For example:
Map<Long, String> monthTexts = new HashMap<>(16);
monthTexts.put(1L, "Jan.");
monthTexts.put(2L, "Feb.");
monthTexts.put(3L, "Mär.");
monthTexts.put(4L, "Apr.");
monthTexts.put(5L, "Mai");
monthTexts.put(6L, "Jun.");
monthTexts.put(7L, "Jul.");
monthTexts.put(8L, "Aug.");
monthTexts.put(9L, "Sep.");
monthTexts.put(10L, "Okt");
monthTexts.put(11L, "Nov.");
monthTexts.put(12L, "Dez.");
DateTimeFormatter monthFormatter = new DateTimeFormatterBuilder()
.appendText(ChronoField.MONTH_OF_YEAR, monthTexts)
.appendPattern(" u")
.toFormatter();
String dateString = from.format(monthFormatter) + " – " + to.format(monthFormatter);
System.out.println(dateString);
Mai 2012 – Nov. 2013
Java 6 and 7 answer to the side question: get the ThreeTen Backport Library and do as in Java 8 (link at the bottom).
For the main question I don’t think I understood it. If what you want is that the ‘to’ months line up vertically, I think you need two columns in your docx document rather than one. You may specify that no vertical line be drawn between those two specific columns so the reader will see it as one.
java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).