首页 > 解决方案 > 如何将时间戳值设置为获取服务的@RequestParam 变量?

问题描述

我有一个@GetMapping带有 3 个请求参数的映射控制器方法:idstartDateendDate.

我希望它接受两个日期参数的时间戳,但只能使用 ISO 格式的字符串让它工作。

我的方法如下所示:

@GetMapping("/getNumberOfHolidays")
public ResponseEntity<Properties> getNumberOfHolidays(@RequestParam Integer locationId, 
        @RequestParam("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date startDate,
        @RequestParam("endDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date endDate){
    Integer noOfDays = 0;
    Properties prop = new Properties();
    try {
        noOfDays = service.getNumberOfHolidays(locationId, startDate, endDate);
        prop.setProperty("Number of Holidays", noOfDays.toString());
    } catch(Exception e) {
        //return
    }
     //return
}

startDate = 2020-08-01当我使用and endDate = 2020-08-10(都在 中)调用此方法时YYYY-mm-DD,它按预期工作并正确转换来自 url 的字符串。

例子:

   http://localhost:8080/TrackContract/getNumberOfHolidays?locationId=2&startDate=2020-08-01&endDate=2020-08-10

但是当我用时间戳调用方法时startDate = 1596220200000endDate = 1596997800000不起作用(在邮递员中给出 400 Bad Request)

例子:

   http://localhost:8080/TrackContract/getNumberOfHolidays?locationId=2&startDate=1596220200000&endDate=1596997800000

我尝试将时间戳值设置为请求参数,如下所示:

       @RequestParam("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
       @RequestParam("endDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate

但这没有用。有人可以在这里帮助我如何将时间戳值设置为 RequestParam startDate 和 endDate?

标签: javaspringspring-bootdate

解决方案


1596220200000不是日期,而是数字。

在这种情况下,它是一个可以解释为自纪元以来的毫秒数的数字,但它只是一个数字。要转换为日期,您必须这样做。

public ResponseEntity<Properties> getNumberOfHolidays(@RequestParam Integer locationId, 
        @RequestParam("startDate") long startMilli,
        @RequestParam("endDate") long endMilli) {
    Instant startInstant = Instant.ofEpochMilli(startMilli);
    Instant endInstant = Instant.ofEpochMilli(endMilli);

在问题中,有两个例子:

startDate = 2020-08-01 and endDate = 2020-08-10
startDate = 1596220200000 and endDate = 1596997800000

然而,15962202000002020-07-31T18:30:00Z
15969978000002020-08-09T18:30:00Z

假设它旨在产生相同的日期值是第一个示例,则必须将日期调整为印度时区。

ZoneId zone = ZoneId.of("Asia/Kolkata");
ZonedDateTime startDateTime = startInstant.atZone(zone);
ZonedDateTime endDateTime = endInstant.atZone(zone);

这将产生价值2020-08-01T00:00+05:30[Asia/Kolkata]2020-08-10T00:00+05:30[Asia/Kolkata]

然后,您可以调用toLocalDate()get2020-08-012020-08-10


推荐阅读