Do we have any API\'s to validate if a date is valid or not when date is having EDT/EST in it. I have tried with Joda, Java SimpleDateFormat but i am not able to parse the date.
Did you try reading the documentation?
From the documentation of DateTimeFormatter:
z time-zone name zone-name Pacific Standard Time; PST
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Zone names: This outputs the display name of the time-zone ID. If the count of letters is one, two or three, then the short name is output. …
Offset X and x: This formats the offset based on the number of pattern letters. … Two letters outputs the hour and minute, without a colon, such as '+0130'. …
So let’s try that:
ZonedDateTime zdt = ZonedDateTime.parse("2017/09/25 16:18:15.099 -0400 EDT",
DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS xx zzz", Locale.ENGLISH));
This produces a ZonedDateTime
of 2017-09-25T16:18:15.099-04:00[America/New_York]
.
Validation
In the code above ZonedDateTime
picks up the time zone from your string and ignores the offset. To validate that the two agree, we can parse the same string both into a ZonedDateTime
and into an OffsetDateTime
and compare. The latter picks up the offset and ignores the time zone abbreviation, so this will work:
String inputDateTimeWithZone = "2017/09/25 16:18:15.099 -0400 EDT";
DateTimeFormatter formatterWithOffsetAndZone
= DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS xx zzz", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(inputDateTimeWithZone,
formatterWithOffsetAndZone);
OffsetDateTime odt = OffsetDateTime.parse(inputDateTimeWithZone,
formatterWithOffsetAndZone);
if (! zdt.toOffsetDateTime().equals(odt)) {
System.err.println("Offset does not match: is " + odt.getOffset()
+ ", but time zone " + zdt.getZone() + " implies offset " + zdt.getOffset());
}
Avoid the three letter time zone abbreviations where you can
EST and EDT may also be used about Australian Eastern Standard and Daylight Time, respectively. Three letter time zone abbreviations are not standardized and are often ambiguous. It would be safer if you either could get a string with a time zone ID in the region/city format (like America/New_York) or you simply stripped off the abbreviation and relied on the offset alone, since this is unambiguous.
The modern Java date and time API
Today I recommend java.time
, AKA JSR-310, over Joda-Time and certainly over the long outdated classes SimpleDateFormat
and Date
. To me it’s proven very nice to work with, and it certainly doesn’t come with the surprises of the old classes. It’s built-in with Java 8 and later. If using Java 6 or 7, you may be tempted to consider Joda-Time at first, but if you’re ready to accept an external dependency, why not take the ThreeTen Backport, the backport of java.time
to Java 6 and 7?