首页 > 解决方案 > micronaut 将请求参数转换为 Instant 或 ZonedDateTime

问题描述

我正在使用 Micronaut 1.3.4,并且正在尝试将输入转换为 Instant。到目前为止,我尝试了很多方法,但没有成功。以下代码仅显示了我尝试过的两种情况,但均未奏效。

我想将输入日期转换为InstantOffsetDateTime

    @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 做到这一点。

标签: 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);
}

转换为简单的地方Instanttime.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}}}

推荐阅读