I need to define date in this format 1999-05-31T13:20:00-05:00
I am using below code
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD'T'hh:mm:ssZ");
sdf.setTimeZone(TimeZone.getTimeZone("EST"));
String date = sdf.format(new Date());
System.out.println(date);
but it is generating date in format 2017-04-117T08:28:46-0500 (missing semicolon in timezone)
After defining the date I have to create an instance of XMLGregorianCalendar with same date.
解决方案
I was surprised you didn’t find the answer when searching for it. Anyway, it’s easy. Two words of caution first, though:
Skip the three-letter time zone abbreviations. Many are ambiguous. While I think EST only means Eastern Standard Time, this isn’t a full time zone, since (most of?) that zone is on EDT now, which does not make it very clear what result you want.
If there’s any way you can, skip the old-fashioned classes SimpleDateFormat, TimeZone and Date. The new classes in java.time are generally much nicer to work with.
The format you are asking for is exactly what DateTimeFormatter.ISO_OFFSET_DATE_TIME is giving you. If you meant to have the time formatted suitably for a user in the Eastern time zone, use:
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/New_York"))
.truncatedTo(ChronoUnit.SECONDS);
System.out.println(now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
Note the use of the unambiguous time zone ID and of the mentioned formatter. The format will print milliseconds (and even smaller) if there are any, which you didn’t ask for. So I have cheated a bit: I am truncating the time to whole seconds. Now this prints something like:
2017-04-27T10:11:33-04:00
If instead you wanted the offset -05:00, that’s even easier:
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.ofHours(-5))
.truncatedTo(ChronoUnit.SECONDS);
System.out.println(now);
This prints something in the same format, but with the desired offset:
2017-04-27T09:11:33-05:00
The toString method of OffsetDateTime gives you the format you want. Of course, if you prefer, you can use the same formatter as before.
If truncating to seconds is a bit too much cheating for your taste, you may of course use a formatter without milliseconds:
DateTimeFormatter isoNoSeconds = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
System.out.println(now.format(isoNoSeconds));
This will work with both a ZonedDateTime and an OffsetDateTime, that is, with both of the above snippets.