我使用SimpleDateFormat(" dd/mm"(的当前显示,例如显示今天的日期为18/04。但是我不想在4个之前显示零,即我只希望它是18/4。我通过使用SimpleDateFormat(" DD/M"(实现了这一点。
我的疑问是,十月通过Decemeber几个月来显示什么?我猜这将截断一位数字,每个月只显示1个数字。
我想要的是能够在这三个月内显示两位数,但在所有其他月份都忽略了零。除了编写一个If-then-else代码块外,是否有一种直接的方法来完成此操作?
通过测试SimpleDateFormat(" DD/M"(,我看到的是您所期望的几个月的行为:在1位数月中不添加零零,但不会切断2位数月。这是11月的一个例子:
@Test
public void shouldPrintNovemberWithTwoDigits() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M");
Date november = DateTime.now().plusMonths(6).toDate();
String expectedDate = "18/10";
String actualDate = simpleDateFormat.format(november);
assertThat(actualDate, is(expectedDate));
}
这是四月(当月(:
@Test
public void shouldPrintAprilWithOneDigit() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M");
Date april = DateTime.now().toDate();
String expectedDate = "18/4";
String actualDate = simpleDateFormat.format(april);
assertThat(actualDate, is(expectedDate));
}
两个测试通过..试试看..