0

I did a lot of searches trying to find this solution. Messing with dates in Java gives me a headache. Most of the results I found were using math to find a previous date or about finding a date offset from today's date. I really needed something from a predefined date (not today). I messed with a lot of classes and code before finding what I needed.

This is also my first post here. I'm a veteran lurker. I hope this saves someone the time I took to find this.

Submit date Dec 2, 2014 and find the date from the week before.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class FilenameDateFormat {

    SimpleDateFormat fileDateFormat = new SimpleDateFormat("yyyyMMdd");

    public static void main(String[] args) throws ParseException {

        new FilenameDateFormat("20141202", -7);
    }

    public FilenameDateFormat(String dateArg, int offsetDays) throws ParseException {

        Date fileDate = fileDateFormat.parse(dateArg);
        Calendar cal = new GregorianCalendar();
        cal.setTime(fileDate);

        cal.add(Calendar.DAY_OF_MONTH, offsetDays);

        System.out.println(cal.getTime());
    }
}

RESULT Tue Nov 25 00:00:00 EST 2014

Sherlock
  • 81
  • 1
  • 2
  • 1
    Thanks for posting, but you should have asked a question and then _answered_ it yourself. Or better yet just ask the question and maybe see if you get any other answers. – Tim Biegeleisen Jan 20 '17 at 15:11
  • @Sherlock (A) FYI, the old [`Calendar`](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html) and [`Date`](http://docs.oracle.com/javase/8/docs/api/java/util/Date.html) classes are now [legacy](https://en.wikipedia.org/wiki/Legacy_system). Supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. (B) Your code ignores the crucial issue of time zone which may lead to unexpected/incorrect results. – Basil Bourque Jan 21 '17 at 00:26

2 Answers2

1

Why dont you use new java.time api ? This could be easily acomplished in java8. https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

molok
  • 31
  • 4
0

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?

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154