本文将带您了解关于将localDateTime字符串正确解析为springboot@pathVariable的新内容,同时我们还将为您解释javalocaldate转string的相关知识,另外,我们
本文将带您了解关于将localDateTime字符串正确解析为spring boot @pathVariable的新内容,同时我们还将为您解释java localdate转string的相关知识,另外,我们还将为您提供关于java – Spring Hateoas,PathVariable和SaxSerialization、java – ZonedDateTime作为Spring REST RequestMapping中的PathVariable、java – 从LocalDateTime字符串到LocalDate的Joda-time、java – 使用Spring Batch将日期从文件解析为LocalDateTime的实用信息。
本文目录一览:- 将localDateTime字符串正确解析为spring boot @pathVariable(java localdate转string)
- java – Spring Hateoas,PathVariable和SaxSerialization
- java – ZonedDateTime作为Spring REST RequestMapping中的PathVariable
- java – 从LocalDateTime字符串到LocalDate的Joda-time
- java – 使用Spring Batch将日期从文件解析为LocalDateTime
将localDateTime字符串正确解析为spring boot @pathVariable(java localdate转string)
我正在尝试获取具有时间戳的用户的所有数据:
@GetMapping("/datum/{userID}/{timeStamp}") List<Datum> getDataSingleUserTimeRange(@PathVariable Long userID, @PathVariable LocalDateTime timeStamp) { .... }
现在要测试这个Spring Boot rest api,在邮递员中,我打电话GET
和url-http://localhost:8080/datum/2/2019-12-15T19:37:15.330995
。
但这给了我错误提示: 无法将类型’java.lang.String’的值转换为所需的类型’java.time.LocalDateTime’
我该如何解决?
答案1
小编典典我不知道这是否是最适度的方法,但这是我所做的:
@GetMapping("/datum/{userID}/{timeStamp}") List<Datum> getDataSingleUserTimeRange(@PathVariable Long userID, @PathVariable String timeStamp) { DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; LocalDateTime dateTime = LocalDateTime.parse(timeStamp, formatter); ... return datumRepository.findUsingTime(start,end); }
作为字符串传递并进行解析。并且dateTime.truncatedTo(ChronoUnit.NECESARRY_UNIT);
可以使用。
java – Spring Hateoas,PathVariable和SaxSerialization
事实上,当我使用类似的东西:
@RequestMapping(value = "/directories/{idDirectory}",method = RequestMethod.GET) public DirectoryDTO findById(@PathVariable String idDirectory) { DirectoryEntity directoryEntity = directoryService.findById(idDirectory); DirectoryDTO directoryDto = new DirectoryDTO(directoryEntity); directoryDto.add(linkTo(methodon(DirectoryController.class).findById(idDirectory)).withSelfRel()); return directoryDto; }
我有一个像下面这样的错误:
[com.sun.istack.internal.SAXException2]: unable to marshal type DirectoryDTO
to element because it’s missing an annotation
这是我的DirectoryEntity:
@Document(collection = "directory") public class DirectoryEntity { @Id private String id; private String name; private String path; private List<DirectoryEntity> childrenDirectories; private DirectoryEntity parentDirectory; private List<FileEntity> fileEntities; /* Get/set omitted */ }
和DTO:
public class DirectoryDTO extends Resource<DirectoryEntity> { public DirectoryDTO(DirectoryEntity content,Link... links) { super(content,links); } public DirectoryDTO(DirectoryEntity content,Iterable<Link> links) { super(content,links); } }
我究竟做错了什么 ?
解决方法
java – ZonedDateTime作为Spring REST RequestMapping中的PathVariable
@RequestMapping(value="/customer/device/startDate/{startDate}/endDate/{endDate}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) public Page<DeviceInfo> getDeviceListForCustomerBetweenDates(@PathVariable zoneddatetime startDate,@PathVariable zoneddatetime endDate,Pageable pageable) { ... code here ... }
我试过传递路径变量作为毫秒和秒.但是,我从两个方面得到以下异常:
"Failed to convert value of type 'java.lang.String' to required type 'java.time.zoneddatetime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.web.bind.annotation.PathVariable java.time.zoneddatetime for value '1446361200'; nested exception is java.time.format.DateTimeParseException: Text '1446361200' Could not be parsed at index 10"
有人可以解释我如何传入(如秒或毫秒)字符串,如1446361200,并让它转换为zoneddatetime?
或者是作为String传递然后自己进行转换的唯一方法?如果是这样,有一种通用的方法来处理具有类似设计的多种方法吗?
解决方法
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
就你而言,这可能是任何FormatStyle或任何DateTimeFormatter,你的例子不会有效. DateTimeFormatter解析并格式化为日期字符串,而不是时间戳,这是您提供的.
您可以为参数提供适当的自定义@org.springframework.format.annotation.DateTimeFormat
,例如
public Page<DeviceInfo> getDeviceListForCustomerBetweenDates( @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) zoneddatetime startDate,@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) zoneddatetime endDate,Pageable pageable) { ...
或者使用适当的pattern
和相应的日期字符串
2000-10-31T01:30:00.000-05:00
您将无法使用unix时间戳执行上述任何操作. The canonical way给zoneddatetime转换的时间戳是通过Instant#ofEpochSecond(long)
,给出一个合适的ZoneId.
long startTime = 1446361200L; zoneddatetime start = Instant.ofEpochSecond(startTime).atZone(ZoneId.systemDefault()); System.out.println(start);
要使其与@PathVariable一起使用,请注册一个自定义Converter.就像是
class zoneddatetimeConverter implements Converter<String,zoneddatetime> { private final ZoneId zoneId; public zoneddatetimeConverter(ZoneId zoneId) { this.zoneId = zoneId; } @Override public zoneddatetime convert(String source) { long startTime = Long.parseLong(source); return Instant.ofEpochSecond(startTime).atZone(zoneId); } }
并在WebMvcConfigurationSupport
@Configuration注释类中注册它,覆盖addFormatters
@Override protected void addFormatters(FormatterRegistry registry) { registry.addConverter(new zoneddatetimeConverter(ZoneId.systemDefault())); }
现在,Spring MVC将使用此转换器将String路径段反序列化为zoneddatetime对象.
在Spring Boot中,我认为你可以为相应的Converter声明一个@Bean,它会自动注册它,但是不要接受我的话.
java – 从LocalDateTime字符串到LocalDate的Joda-time
我正在使用JodaTime来获取创建帐户的日期和时间.格式是
2017-04-05T12:38:35.585
当我得到它时,我将它作为字符串存储在我的数据库中,所以我一直在寻找将字符串格式化为LocalDate的方法,但在我在网上找到的任何内容都没有成功.我的下一步是一个可怕的解决方案,在我看来循环遍历字符串,直到我找到T并删除它之后的所有内容.所以我离开了
2017-04-05.
但理想情况下,如果可能的话,日期为
05/04/2017
解决方法:
使用ISODateTimeFormat获取LocalDateTime并从中获取LocalDate.
小心使用正确的区域设置
String input="2017-04-05T12:38:35.585";
LocalDateTime ldt = ISODateTimeFormat.localDateOptionalTimeParser()
.withLocale(Locale.ENGLISH)
.parseLocalDateTime(input);
System.out.println(ldt.toLocalDate());//prints 2017-04-05
java – 使用Spring Batch将日期从文件解析为LocalDateTime
Field error in object ‘target’ on field ‘date’: rejected value [2017-07-20 04:15:25.0]; codes [typeMismatch.target.date,typeMismatch.date,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.date,date]; arguments []; default message [date]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.time.LocalDateTime’ for property ‘date’; nested exception is java.lang.IllegalStateException: Cannot convert value of type ‘java.lang.String’ to required type ‘java.time.LocalDateTime’ for property ‘date’: no matching editors or conversion strategy found]
Main.java:
public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(SpringBatchDateParseConfig.class); JobLauncher jobLauncher = context.getBean(JobLauncher.class); Job job = context.getBean("job",Job.class); JobParameters jobParameters = new JobParametersBuilder().toJobParameters(); try { JobExecution jobExecution = jobLauncher.run(job,jobParameters); } catch (Exception e) { e.printstacktrace(); } } }
SpringBatchDateParseConfig.java:
@Configuration @EnableBatchProcessing public class SpringBatchDateParseConfig { @Inject private JobBuilderFactory jobBuilderFactory; @Inject private StepBuilderFactory stepBuilderFactory; @Bean public Step step1() { return stepBuilderFactory.get("step1") .<TestClass,TestClass>chunk(2) .reader(testClassItemReader()) .writer(testClassItemWriter()) .build(); } @Bean public Job job(Step step1) { return jobBuilderFactory.get("job") .start(step1) .build(); } @Bean FlatFileItemReader<TestClass> testClassItemReader() { FlatFileItemReader<TestClass> flatFileItemReader = new FlatFileItemReader<>(); flatFileItemReader.setResource(new ClassPathResource("test.csv")); flatFileItemReader.setLinesToSkip(1); DefaultLineMapper defaultLineMapper = new DefaultLineMapper(); DelimitedLinetokenizer delimitedLinetokenizer = new DelimitedLinetokenizer(); delimitedLinetokenizer.setNames(new String[]{"foo","bar","date"}); BeanWrapperFieldSetMapper<TestClass> fieldSetMapper = new BeanWrapperFieldSetMapper<>(); fieldSetMapper.settargettype(TestClass.class); defaultLineMapper.setLinetokenizer(delimitedLinetokenizer); defaultLineMapper.setFieldSetMapper(fieldSetMapper); flatFileItemReader.setLineMapper(defaultLineMapper); return flatFileItemReader; } @Bean ItemWriter<TestClass> testClassItemWriter() { return new ItemWriter<TestClass>() { @Override public void write(List<? extends TestClass> items) throws Exception { for (TestClass TestClass : items) { System.out.println(TestClass.toString()); } } }; } }
TestClass.java:
public class TestClass { private String foo; private String bar; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME,pattern = "yyyy-MM-dd H:m:s.S") private LocalDateTime date; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; } public LocalDateTime getDate() { return date; } public void setDate(LocalDateTime date) { this.date = date; } }
test.csv:
foo,bar,date asdf,fdsa,2017-07-20 04:15:25.0 qwerty,ytrewq,2017-07-20 04:15:25.0
我错过了什么吗?
解决方法
public class BeanWrapperFieldSetMapperCustom<T> extends BeanWrapperFieldSetMapper<T> { @Override protected void initBinder(DataBinder binder) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); binder.registerCustomEditor(LocalDate.class,new propertyeditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.isNotEmpty(text)) { setValue(LocalDate.parse(text,formatter)); } else { setValue(null); } } @Override public String getAsText() throws IllegalArgumentException { Object date = getValue(); if (date != null) { return formatter.format((LocalDate) date); } else { return ""; } } }); } }
关于将localDateTime字符串正确解析为spring boot @pathVariable和java localdate转string的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于java – Spring Hateoas,PathVariable和SaxSerialization、java – ZonedDateTime作为Spring REST RequestMapping中的PathVariable、java – 从LocalDateTime字符串到LocalDate的Joda-time、java – 使用Spring Batch将日期从文件解析为LocalDateTime等相关内容,可以在本站寻找。
本文标签: