I have an XMLGregorianCalendar date in the below format:
2022-11-23T13:53:31
I want to convert it to ISO_8601 format like below:
2022-11-23T13:53:31.890Z
So I am getting below exception:
java.time.format.DateTimeParseException: Text '2022-11-23T13:53:31' could not be parsed at index 19
I have tried the below code:
public static boolean checkIfDateMatches( String fromDate, String toDate, String inputDate ) throws Exception {
boolean flag = false;
Date start = Date.from(Instant.parse(fromDate));
Date end = Date.from(Instant.parse(toDate));
Date input = Date.from(Instant.parse(inputDate));
if( input.compareTo(start) >= 0 && input.compareTo(end) <= 0 ) {
flag = true;
}
return flag;
}
Any help appreciated. Thank you
CodePudding user response:
If you just want to convert the example input to UTC, you will need to make sure it actually is UTC. Otherwise you would just append a Z
and declare it UTC.
The DateTimeParseException
tells you there's information missing in the String
because a non existent index is attempted to be parsed. The input has a length of 19, so its last index is 18.
That means, in this case, the String
cannot be (reliably) assigned to a zone or offset. Zone and offset are unkown. They have been expected at/from index 19.
If you can verify the input is a UTC time, you can use the following example that makes the input a comparable UTC datetime: An OffsetDateTime
…
public static void main(String[] args) {
// example input WITHOUT OFFSET
String input = "2022-11-23T13:53:31";
// parse it AND DECLARE IT UTC
OffsetDateTime odt = LocalDateTime.parse(input)
.atOffset(ZoneOffset.UTC);
// print the result
String msg = String.format("IN: %s\nOUT: %s",
input,
odt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
System.out.println(msg);
}
Output:
IN: 2022-11-23T13:53:31
OUT: 2022-11-23T13:53:31Z
You can compare OffsetDateTime
s, just have a look at the docs.
If you need the milliseconds / fractions of second, define a custom DateTimeFormatter
.
Remember to make sure the input is UTC.