Merge pull request #51892 from LindseyZ1205

Closes gh-51892

* pr/51892:
  Polish 'Fix formatting a zero period with a weeks unit'
  Fix formatting a zero period with a weeks unit
This commit is contained in:
Phillip Webb
2026-09-28 09:14:44 -07:00
3 changed files with 16 additions and 1 deletions
@@ -31,6 +31,7 @@ import org.springframework.util.Assert;
*
* @author Eddú Meléndez
* @author Edson Chávez
* @author Yingzi Zhang
* @author Valentine Wu
* @since 2.3.0
* @see Period
@@ -262,10 +263,13 @@ public enum PeriodStyle {
}
private boolean isZero(Period value) {
return intValue(value) == 0;
return value.isZero() || intValue(value) == 0;
}
private int intValue(Period value) {
if (value.isZero()) {
return 0;
}
Assert.state(this.intValue != null, () -> "intValue cannot be extracted from " + name());
return this.intValue.apply(value);
}
@@ -29,6 +29,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
*
* @author Eddú Meléndez
* @author Edson Chávez
* @author Yingzi Zhang
* @author Valentine Wu
*/
class PeriodStyleTests {
@@ -220,6 +221,7 @@ class PeriodStyleTests {
void printSimpleWhenZeroWithUnitShouldPrintInUnit() {
Period period = Period.ofYears(0);
assertThat(PeriodStyle.SIMPLE.print(period, ChronoUnit.YEARS)).isEqualTo("0y");
assertThat(PeriodStyle.SIMPLE.print(Period.ZERO, ChronoUnit.WEEKS)).isEqualTo("0w");
}
@Test
@@ -32,6 +32,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*
* @author Eddú Melendez
* @author Edson Chávez
* @author Yingzi Zhang
*/
class PeriodToStringConverterTests {
@@ -63,6 +64,14 @@ class PeriodToStringConverterTests {
assertThat(converted).isEqualTo("0y");
}
@ConversionServiceTest
void convertWithFormatAndWeeksUnitWhenZeroShouldUseFormatAndUnit(ConversionService conversionService) {
String converted = (String) conversionService.convert(Period.ZERO,
MockPeriodTypeDescriptor.get(ChronoUnit.WEEKS, PeriodStyle.SIMPLE),
TypeDescriptor.valueOf(String.class));
assertThat(converted).isEqualTo("0w");
}
@ConversionServiceTest
void convertWithFormatAndUnitWhenNonZeroShouldUseFormatAndIgnoreUnit(ConversionService conversionService) {
String converted = (String) conversionService.convert(Period.of(1, 0, 3),