micronaut - micronaut 将请求参数转换为 Instant 或 ZonedDateTime
问题描述
我正在使用 Micronaut 1.3.4,并且正在尝试将输入转换为 Instant。到目前为止,我尝试了很多方法,但没有成功。以下代码仅显示了我尝试过的两种情况,但均未奏效。
我想将输入日期转换为Instant
或OffsetDateTime
@Get("/...")
public List<Obj> method(
// @Format("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
// Instant startDateTime,
@Format("yyyy-MM-dd")
LocalDate endDateTime
) {
如果可能,我想使用 ISO 8601。
我尝试过的输入:
2013-02-04
2013-02-04T22:44:30.652Z
...
我得到的输出是:
"message": "Required argument [LocalDate endDateTime] not specified",
我的后备是:
String startDateTime
Instant parse = Instant.parse(startDateTime);
OffsetDateTime parse = OffsetDateTime.parse(startDateTime);
但我仍然想知道如何使用 Micronaut 做到这一点。
解决方案
以下是如何LocalDateTime
在 Micronaut 中作为查询参数传递的示例:
@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}}}
推荐阅读
- php - phpseclib 无法读取包含 guillemet 括号的 CSR 字段
- docker - 如何在 kubernetes 中添加 pod 依赖项,就像 docker-compose.yml 中的“depends_on”一样
- youtube - YouTube 还在使用 DASH 吗?
- ios - Scenekit:为什么我的相机看不到远处的物体?
- python - 如何从python中提取HTML文件中的特定行?
- r - 无法启动 rstudio(安装在 Anaconda 中)
- python - 在python中将日期时间写入CSV文件?
- reactjs - 添加导入对象时的括号表示法
- php - 从 API 获取 json 数据,如何以表格格式或引导程序在循环中显示数据
- amazon-web-services - 潜望镜式应用架构