I've got a Calendar
Date in Java.
I need to convert it in a String
with this format :
2020-12-29T00:00:00+01:00
How can I do it?
Thank you so much for your help.
I've got a Calendar
Date in Java.
I need to convert it in a String
with this format :
2020-12-29T00:00:00+01:00
How can I do it?
Thank you so much for your help.
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
Here’s a formatter for your desired format:
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
With this we may do:
ZoneId zone = ZoneId.of("Asia/Barnaul");
ZonedDateTime dateTime
= LocalDate.of(2020, Month.DECEMBER, 29).atStartOfDay(zone);
String formatted = dateTime.format(formatter);
System.out.println(formatted);
Output from this example snipoet is:
2020-12-29T00:00:00+07:00
If you are getting a Calendar
object from a legacy API that you cannot afford to upgrade to java.time just now, convert it to ZonedDateTime
. It is almost certainly really a GregorianCalendar
(or formatting into that format would not make much sense), which makes the conversion straightforward.
Calendar yourCalendar = getCalendarFromLegacyApi();
ZonedDateTime dateTime
= ((GregorianCalendar) yourCalendar).toZonedDateTime();
The rest is as before, as is the output.
If you need to take into account the possibility that the Calendar
is not a GregorianCalendar
, use this slightly more complicated conversion instead:
ZonedDateTime dateTime = yourCalendar.toInstant()
.atZone(yourCalendar.getTimeZone().toZoneId());
Oracle tutorial: Date Time explaining how to use java.time.
Get the
Date
object by callingCalendar#getTime
and format it using aSimpleDateFormat
with the format,yyyy-MM-dd'T'HH:mm:ssXXX
.Note: Since the desired string has timezone offset of
+01:00
hours, make sure you set the timezone of theSimpleDateFormat
object toTimeZone.getTimeZone("GMT+1")
before callingSimpleDateFormat#format
.Demo:
Another example:
Output: