我有一个日期格式模式:MMM yyyy
并且想要:如果月份名称很短,则在名称后面打印一个点。但是,如果月份名称不短,则不会添加任何点。
示例:
May 2010
(不带点) - 5月只有3个字母,因此不需要点,因为它不是缩写。Dec. 2010
(带点) - 12月长度超过3个字母,因此需要一个点,因为它是缩写。这可能是一种模式,还是我需要通过“手”来实现它?
答案 0 :(得分:6)
您可以在格式化程序中使用自定义DateFormatSymbols
,在其中使用包含“May”而非“May”的短数组覆盖短月数组。
更新:抱歉,我最后一点错了,当然应该是相反的,短暂的月份原本是“Jan”,“Feb”等,你应该用“替换它们” 1月“,”2月“除了五月之外的每个月。
答案 1 :(得分:6)
我已经实现了biciclop solution。 - 它有效。
如果有人有兴趣,请点击这里:
import static org.junit.Assert.assertEquals;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import org.junit.Test;
public class DateFormatTest {
/** The locale where the tests are for. */
private static final Locale locale = Locale.ENGLISH;
/**
* Add a dot to all abbricated short months.
*
* @param dateFormatSymbols
* @return
*/
private final DateFormatSymbols addDotToAbbricationMonths(final DateFormatSymbols dateFormatSymbols) {
String[] shortMonths = dateFormatSymbols.getShortMonths();
for (int i = 0; i < shortMonths.length; i++) {
if (dateFormatSymbols.getMonths()[i].length() > shortMonths[i].length()) {
shortMonths[i] += '.';
}
}
dateFormatSymbols.setShortMonths(shortMonths);
return dateFormatSymbols;
}
/** pattern under test. */
final DateFormat format = new SimpleDateFormat("MMM yyyy", addDotToAbbricationMonths(new DateFormatSymbols(locale)));
/** Scenario: May is only 3 letters long, so there is no dot needed, because it is not an abbreviation. */
@Test
public void testShortEnought() {
Date firstMay = new GregorianCalendar(2010, Calendar.MAY, 1).getTime();
assertEquals("May 2010", format.format(firstMay));
}
/** Scenario: December is more than 3 letters long, so there is a dot needed, because it an abbreviation. */
@Test
public void testToLong() {
Date firstDecember = new GregorianCalendar(2010, Calendar.DECEMBER, 1).getTime();
assertEquals("Dec. 2010", format.format(firstDecember));
}
/** Scenario: if the DateFormatSymbols are changed for this special, it should not influence the other formatter. */
@Test
public void noInfluence() {
Date firstDecember = new GregorianCalendar(2010, Calendar.DECEMBER, 1).getTime();
assertEquals("Dec 2010", new SimpleDateFormat("MMM yyyy", locale).format(firstDecember));
}
}