How can I get my date formatted as 2012-11-25T23:50:56.193+01:00
using SimpleDateFormat
?
If I use Z
in the format like
yyyy-MM-dd'T'hh:mm:ss.SSSZ
then it shows
2013-03-06T11:49:05.490+0100
OffsetTime. The OffsetTime class, in effect, combines the LocalTime class with the ZoneOffset class. It is used to represent time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC time (+/-hours:minutes, such as +06:00 or -08:00).
The T separates the date portion from the time-of-day portion. The Z on the end means UTC (that is, an offset-from-UTC of zero hours-minutes-seconds). The Z is pronounced “Zulu”.
DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat , allows for formatting (i.e., date -> text), parsing (text -> date), and normalization.
You can get the timezone offset formatted like +01:00
with the SimpleDateFormat in Java 7 (yyyy-MM-dd'T'HH:mm:ss.SSSXXX
), or with the Joda's DateTimeFormat (yyyy-MM-dd'T'HH:mm:ss.SSSZZ
).
Here’s the 2017 answer. If there is any way you can (which there is), throw the outdated classes like SimpleDateFormat
overboard and use the modern and more convenient classes in java.time
. In particular, the desired format, 2012-11-25T23:50:56.193+01:00
complies with ISO-8601 and therefore comes out of the box with the newer classes, just use OffsetDateTime.toString()
:
OffsetDateTime time = OffsetDateTime.now();
System.out.println(time.toString());
This prints something like
2017-05-10T16:14:20.407+02:00
One thing you may or may not want to be aware of, though, it prints as many groups of 3 decimals on the seconds as it takes to print the precision in the OffsetDateTime
object. Apparently on my computer “now” comes with a precision of milliseconds (seconds with three decimals).
If you have an oldfashioned Date
object, for example, you got it from a call to some legacy method, I recommend the first thing you do is convert it to Instant
, which is one of the modern classes. From there you can easily other conversions depending on your requirements:
Date now = new Date();
OffsetDateTime time = now.toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime();
System.out.println(time.toString());
I am really doing more conversions than necessary. atZone(ZoneId.systemDefault())
produced a ZonedDateTime
, and its toString()
will not always give you the format you said you wanted; but it can easily be formatted into it:
ZonedDateTime time = now.toInstant().atZone(ZoneId.systemDefault());
System.out.println(time.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With