这是一个示例,说明如何在 Micronaut 中将 LocalDateTime 作为查询参数传递:
@Get("/local")
public String local(@Format("yyyy-MM-dd'T'HH:mm:ss") @QueryValue LocalDateTime time) {
return "Time " + DateTimeFormatter.ISO_DATE_TIME.format(time);
}
带有结果的 curl 调用示例:
$ curl http://localhost:8080/example/local?time=2020-04-13T21:13:59
Time 2020-04-13T21:13:59
当时区始终相同时,您可以使用LocalDateTime。你可以把它转换成Instant,像这样time.atZone(ZoneId.systemDefault()).toInstant()。
当时区可以不同并且必须是输入时间的一部分时,您可以像这样使用ZonedDateTime参数:
@Get("/zoned")
public String method(@Format("yyyy-MM-dd'T'HH:mm:ss.SSSZ") @QueryValue ZonedDateTime time) {
return "Time " + DateTimeFormatter.ISO_DATE_TIME.format(time);
}
转换成Instant 很简单:time.toInstant()
带有结果的 curl 调用示例:
$ curl http://localhost:8080/example/zoned?time=2020-04-13T21:13:59.123-0100
Time 2020-04-13T21:13:59.123-01:00
当您以错误的格式输入时间查询参数(此处缺少秒数和区域偏移量)时,其行为如下:
$ curl http://localhost:8080/example/zoned?time=2020-04-13T21:13:59
{"message":"Required QueryValue [time] not specified","path":"/time","_links":{"self":{"href":"/example/zoned?time=2020-04-13T21:13:59","templated":false}}}
您也可以使用时间作为请求路径的一部分:
@Get("/local/{time}")
public String local(@Format("yyyy-MM-dd'T'HH:mm:ss") LocalDateTime time) {
return "Time from request path " + DateTimeFormatter.ISO_DATE_TIME.format(time);
}
那么示例 curl 调用将是:
$ curl http://localhost:8080/example/local/2020-04-13T21:13:59
Time from request path 2020-04-13T21:13:59
当您在路径中输入错误格式的时间(此处不需要的秒数)时,它的行为如下:
$ curl http://localhost:8080/example/local/2020-04-13T21:13:59.111
{"message":"Failed to convert argument [time] for value [2020-04-13T21:13:59.111] due to: Text '2020-04-13T21:13:59.111' could not be parsed, unparsed text found at index 19","path":"/time","_links":{"self":{"href":"/example/local/2020-04-13T21:13:59.111","templated":false}}}