I am using java 11. Wanted to know whats the best(Most importantly Recommended) way to validate if the datetime string is ISO8601 complaint in java.
Also how to compare this string value with java.sql.Timestamp?
ISO 8601 is so many things, so I am not going to write an exhaustive answer. I am trying to give an overview of the options that you will likely choose from. After that you should research the relevant one/s further. And maybe before doing that you will need to research what ISO 8601 is, what it can sometimes be and what it isn’t.
For many (most) purposes trying to parse your string with built-in means of java.time, the modern Java date and time API, will give you a satisfactory validation, as already stated in the other answers. Options are:
parse
method of the appropriate date-time class from java.time. They generally parse ISO 8601 format and throw a DateTimeParseException
if the string is not in ISO 8601 format. Depending on the information required to be present in your string (date and/or time, UTC offset) you may for example use OffsetDateTime.parse()
or LocalDate.parse()
.ISO_XXXX
constants of the DateTimeFormatter
class.There are at least three ways that the above may not be enough for you:
OffsetDateTime.parse(CharSequence)
requires a colon in the offset from UTC (if it is not Z
), as in +07:00
. ISO 8601 also allows the offset to be written without a colon, as in +0700
. If you need to accommodate variants not covered by the built-in means, building your own DateTimeFormatter
will probably be a good and not too complicated solution. You may use the DateTimeForamtter.ofPattern
method or a DateTimeFormatterBuilder
.isBefore
and isAfter
for this.If you can avoid using java.sql.Timestamp
, do. That class is poorly designed and long outdated. Since JDBC 4.2 we prefer fetching timestamps as OffsetDateTime
or LocalDateTime
from our SQL databases.
If you have got a Timestamp
from a legacy API that you cannot afford to upgrade just now, convert each to an Instant
and compare them using isBefore()
or isAfter()
. Here’s an example:
String yourIso8601String = "2020-11-17T02:51:39.375109+07:00";
Timestamp ts = Timestamp.from(Instant.parse("2020-11-16T19:00:00Z"));
OffsetDateTime odt = OffsetDateTime.parse(yourIso8601String);
boolean isBeforeTimestamp = odt.toInstant().isBefore(ts.toInstant());
System.out.println("Is the ISO 8601 string before the Timestamp? " + isBeforeTimestamp);
Output from the example is:
Is the ISO 8601 string before the Timestamp? false