无法使用 DefaultFormattingConversionService 从字符串转换为 Joda LocalTime

Can't convert from string to Joda LocalTime with DefaultFormattingConversionService

无法使用 DefaultFormattingConversionService.

将字符串转换为 Joda LocalTime

如果我将时间传递为​​“12:00”,它说时间太短,但如果我将它传递为“12:00:00”,它说它格式错误。

import org.joda.time.LocalTime;
import org.springframework.format.support.DefaultFormattingConversionService;

public class SpringLocalTimeFormatterTry {

   public static void main(String[] args) {

      DefaultFormattingConversionService service = new DefaultFormattingConversionService();
      try {
         System.out.println(service.convert("12:00", LocalTime.class));
      }
      catch (Exception e) {
         System.out.println(e.getMessage());
      }
      try {
         System.out.println(service.convert("12:00:00", LocalTime.class));
      }
      catch (Exception e) {
         System.out.println(e.getMessage());
      }


   }
}

如何正确使用或修复?

试试这个:

DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm:ss");
LocalTime localTime = dtf.parseLocalTime("12:00:00");
System.out.println("Time"+localTime);

DefaultFormattingConversionService 的原始设置使用平台默认区域设置,我从错误中假设它与我的相同,即。英语。这意味着,您需要暂时添加 AM/PM 指标。这对我有用:

System.out.println(service.convert("10:12 am", LocalTime.class));

>> 10:12:00.000

要处理您想要的时间格式,您可以添加一个额外的转换器:

service.addConverter(new Converter<String, LocalTime>() {
    @Override
    public LocalTime convert(String source) {
        return LocalTime.parse(source);
    }
});

那么,两个例子都通过了:

System.out.println(service.convert("12:00", LocalTime.class));
>> 12:00:00.000
System.out.println(service.convert("12:00:00", LocalTime.class));
>> 12:00:00.000

您可以通过使用

创建服务来跳过注册默认转换器
new DefaultFormattingConversionService(false);

最后,我假设在生产代码中您实际上是从 ConversionServiceFactoryBean 获取 ConversionService,因此您可以按如下方式配置:

@Bean
public ConversionServiceFactoryBean conversionService() {
    ConversionServiceFactoryBean conversionServiceFactoryBean = new ConversionServiceFactoryBean();
    Set<Converter<?, ?>> myConverters = new HashSet<>();
    myConverters.add(new Converter<String, LocalTime>() {
        @Override
        public LocalTime convert(String source) {
            return LocalTime.parse(source);
        }
    });
    conversionServiceFactoryBean.setConverters(myConverters);
    return conversionServiceFactoryBean;
}