Java get the date X days later

I am setting up a db40 database, and it is filled with instances of my class Day() which has sales information for that day in history, and an integer for its ID. The id is formatted like so: YYYYMMDD, so that they are all unique. My db is set up with the correct data chronologically, but right now I am forced to go in and edit the id's manually for over a year's worth of data.

Question: assuming day 1 is January 1, 2014 which would be formatted: 20140101, how do I correctly increment the date by one day each time? I have 424 dates I need to calculate after that, but I can't think of a clever solution without brute forcing it.

So ideally, i would want something like this getDate(ThisDate+1 Day)

Jon Skeet
people
quotationmark

As you're using Java 8, I'd use java.time for this:

  • Convert the integer (ick) into a LocalDate
  • Add however many days you want
  • Convert back to an integer (ick)

So something like:

static LocalDate dateFromId(int id) {
    int year = id / 10000;
    int month = (id / 100) % 100;
    int day = id % 100;
    return LocalDate.of(year, month, day);
}

static int idFromDate(LocalDate date) {
    return date.getYear * 10000
        + date.getMonthValue() * 100 
        + date.getDayOfMonth();
}

static int advanceId(int id, int days) {
    LocalDate original = dateFromId(id);
    LocalDate advanced = original.plusDays(days);
    return idFromDate(advanced);
}

Or to compute a bunch of them:

LocalDate original = dateFromId(id);
for (int i = 1; i <= count; i++) {
    LocalDate advanced = original.plusDays(i);
    int advancedId = idFromDate(advanced);
    // Use advanced
}

people

See more on this question at Stackoverflow