Karlovsky120
Karlovsky120

Reputation: 6362

adding/removing days from date code fix needed

I have this code here:

public static String AddRemoveDays(String date, int days) throws ParseException
    {
        SimpleDateFormat k = new SimpleDateFormat("yyyyMMdd");
        Date d = k.parse(date);
        d = new Date(d.getTime() + days*86400000);
        String time = k.format(d);

        return time;
    }

It take String formed "yyyyMMdd", and adds int days to it. It should work then the days is negative - then he would substract the days from the date. When it does it's math, it returns String formated "yyyyMMdd".

At least that is what it should do. It works for small numbers, but if I try to add (or remove), for example, a year (365 or -365), it returns wierd dates.

What's the problem? Should I do it a completley another way?

Upvotes: 0

Views: 2214

Answers (2)

amaidment
amaidment

Reputation: 7298

Hard to say what's going on without specific dates.

If you're committed to doing this with the raw Java classes, you might want to look at using Calendar -e.g.

Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.add(Calendar.DATE, days); // this supports negative values for days;
d = calendar.getTime();

That said, I would recommend steering clear of the java Date classes, and look to use jodaTime or jsr310 instead.

e.g. in jsr310, you could use a DateTimeFormatter and LocalDate:

DateTimeFormatter format = DateTimeFormatters.pattern("yyyyMMdd");
LocalDate orig = format.parse(dateString, LocalDate.rule());
LocalDate inc = orig.plusDays(days); // again, days can be negative;
return format.print(inc);

Upvotes: 2

Pshemo
Pshemo

Reputation: 124275

    d = new Date(d.getTime() + days*86400000);

If you multiply 86400000 by 365 integer cant hold it. Change 86400000 to Long

    d = new Date(d.getTime() + days*86400000L);

and it will be fine.

Upvotes: 5

Related Questions