dd/MM 10 月-11 月-12 月,其他月份 dd/M - SimpleDateFormat
dd/MM for Oct-Nov-Dec, other months dd/M - SimpleDateFormat
我目前正在使用 SimpleDateFormat("dd/MM"),它显示例如今天的日期为 18/04。但我不想在 4 之前显示零,即我希望它只有 18/4。这是我通过使用 SimpleDateFormat("dd/M") 实现的。
我的疑问是,10 月到 12 月会显示什么?我猜它会截断一位数字,并且每个月只显示 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));
}
这是 4 月(当月):
@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));
}
两个测试都通过了..试试吧..
我目前正在使用 SimpleDateFormat("dd/MM"),它显示例如今天的日期为 18/04。但我不想在 4 之前显示零,即我希望它只有 18/4。这是我通过使用 SimpleDateFormat("dd/M") 实现的。
我的疑问是,10 月到 12 月会显示什么?我猜它会截断一位数字,并且每个月只显示 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));
}
这是 4 月(当月):
@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));
}
两个测试都通过了..试试吧..