java.time
String fromDateTime = OffsetDateTime.now(ZoneId.systemDefault()).minusMonths(6).toString();
System.out.println(fromDateTime);
Output when running on my computer just now:
2018-08-04T12:45:34.087966+01:00
java.time is the modern Java date and time API and has effectively replaced Joda-Time. From the home page:
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time
(JSR-310).
In the code I am taking advantage of the fact that the java.time classes’ toString
methods produce ISO 8601 format, the format you were asking for. I find it unlikely that the extra decimals on the seconds will pose any problem since thay are allowed within the standard.
Joda-Time
String fromDateTime = new DateTime().minusMonths(6).toString();
Example output:
2018-08-04T12:50:36.071+02:00
new DateTime()
only has millisecond precision. You will always get exactly 3 decimals on the seconds.
I gotta use old java libraries, cause I work for a company that uses java version < 8
java.time works nicely on Java 6 and 7 too, and all things being equal I recommend it over Joda-Time. Only if forced to use Java 5, Joda-Time is no doubt the good choice.
- In Java 8 and later and on newer Android devices (from API level 26) java.time comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
What went wrong in your code?
Your code can be compiled without signs of errors, but issues a java.lang.IllegalArgumentException: Cannot format given Object as a Date
when run. This is because a SimpleDateFormat
cannot format a Joda-Time DateTime
object. We would of course have expected this to be reported on compile time. But in addition to SimpleDateFormat.format(Date)
there is also an overridden format(Object)
inherited from Format
. It works for formatting either a Date
or a Number
(for milliseconds since the epoch). This method is the one that the compiler chooses when you pass a DateTime
. Which is why there is no compile-time error message.
Tip: When you don’t immediately understand an error message, paste it into your search engine. It will very often lead you to an explanation and a solution. Also in this case.
Links