I'm working on a example project where we need to store some values in a Hashmap and fetch them via REST services.
POSTing the data as
{"timestamp":"2015-09-01T16:40:00.000Z", "temperature":"27.2"}
Save method:
@PostMapping
public ResponseEntity<?> createCalc(@Valid @RequestBody Calc calc) {
store.add(measurement);
}
...
Store class
private HashMap<ZonedDateTime, Calc> calcHashMap;
...
public void add(Calc calc) {
calcHashMap.put(calc.getTimestamp(), calc);
}
After saving we wanted to get data from Hashmap, none of the below can find it.
http://localhost:8000/measurements/2015-09-01T16:40:00.000Z
or
http://localhost:8000/measurements/2015-09-01T16:40Z
Method we are using is
@GetMapping("/{timestamp}")
public ResponseEntity<Calc> getCalc(@PathVariable ZonedDateTime timestamp) {
Calc calc = process.fetch(timestamp);
Process.java class
public Calc fetch(ZonedDateTime timestamp) {
return calcMap.get(timestamp);
}
Adding that to a Hashmap and Timestamp as the key. We are seeing these differences:
I need to find the stores timestamp and return the object, but is not being found because of the differences above. How to solve this?
After some research i was able to solve this as below
for (ZonedDateTime zdt : measurementHashMap.keySet()) {
if (timestamp.toInstant().compareTo(measurementHashMap.get(zdt).getTimestamp().toInstant()) == 0) {
return measurementHashMap.get(zdt);
}
}
Option 2: There is another option to convert ZonedDateTime to OffSetDate and then compare. Ref: https://rextester.com/SIIIW97667
In your Calc
class, you can use @JsonFormat
from Jackson library and give the required pattern you want. In this case, "yyyy-MM-dd'T'HH:mm:ss.SSSX". Also, I suggest you to use OffsetDateTime
directly instead of conversion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.