java - 如何将时间戳值设置为获取服务的@RequestParam 变量?
问题描述
我有一个@GetMapping
带有 3 个请求参数的映射控制器方法:id
、startDate
和endDate
.
我希望它接受两个日期参数的时间戳,但只能使用 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 = 1596220200000
它endDate = 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?
解决方案
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
然而,1596220200000
是2020-07-31T18:30:00Z
和1596997800000
是2020-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-01
和2020-08-10
。
推荐阅读
- jquery - 我在 jquery ajax 中有一个脚本并且不工作如何修复错误
- scheme - Nested Recursion and McCarthy's 91 Function
- mongodb - MongoDB总和与匹配
- android - How to fix "java.lang.IndexOutOfBoundsException: Inconsistency detected."
- algorithm - Left to Right Alpha-Beta Pruning
- java - Some test cases satisfied while others not
- dialogflow-es - Dialogflow 上的上下文和回退
- django - 当外键不在当前模型中时,如何获取模型的查询集的值?
- windows - 批处理脚本后继续使用 CMD 命令
- keras - Keras:编译后更改 LSTM 参数 return_sequences=True