tl;dr
LocalDate.parse(
"20141202" ,
DateTimeFormatter.BASIC_ISO_DATE
).minusWeeks( 1 )
2014-11-25
Avoid legacy date-time classes
Messing with dates in Java gives me a headache.
Date-time work in general is tricky, slippery, elusive.
And using the troublesome old date-time classes (java.util.Date
, java.util.Calendar
, etc.) makes the work all the more difficult. Those old classes are now legacy, supplanted by the java.time classes.
LocalDate
Submit date Dec 2, 2014
The LocalDate
class represents a date-only value without time-of-day and without time zone.
Your input string happens to be in the “basic” version of the standard ISO 8601 format. The canonical version includes hyphens, 2014-12-02
, while the “basic” version minimizes the use of separators, 20141202
. I strongly suggest using the fuller version when possible to improve readability and reduce ambiguity/confusion.
DateTimeFormatter
The DateTimeFormatter
class includes a pre-defined formatting pattern for your input, DateTimeFormatter.BASIC_ISO_DATE
.
String input = "20141202" ;
DateTimeFormatter f = DateTimeFormatter.BASIC_ISO_DATE ;
LocalDate ld = LocalDate.parse( input , f );
In real code, trap for the DateTimeParseException
being thrown because of bad input.
String input = "20141202" ;
DateTimeFormatter f = DateTimeFormatter.BASIC_ISO_DATE ;
LocalDate ld = null;
try{
ld = LocalDate.parse( input , f );
} catch ( DateTimeParseException e ) {
… // Handle error because of bad input.
}
Subtracting a week
find the date from the week before
Subtract a week. Note that java.time uses immutable objects. So rather than alter (mutate) the values in an object, we generate a new and separate object based on the original’s values.
LocalDate oneWeekAgo = ld.minusWeeks( 1 );
input: 20141202
ld.toString(): 2014-12-02
oneWeekAgo.toString(): 2014-11-25
See live code in IdeOne.com.
If you want a String in the same format as the input, use the same formatter seen above.
String output = oneWeekAgo.format( DateTimeFormatter.BASIC_ISO_DATE );
20141125
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.