1
votes

So I've got this kind of strange problem with Java's Date.

The entry-point for this problem are 2 String dates startDate("30 Jan 2016") and endate ""29 Jan 2017".

The problem is a little bit more complex,but I've summed it up just to this case.

What I have to do is get an 1 year schedule exactly like the one from bellow starting with this data.

The table contains for each month: first day, last day, and days between those 2 days.

Expected results:

/**

  • Sat Jan 30 00:00:00 GMT 2016 - Sun Feb 28 23:59:59 GMT 2016 - 30

  • Mon Feb 29 00:00:00 GMT 2016 - Tue Mar 29 23:59:59 BST 2016 - 30

  • Wed Mar 30 00:00:00 BST 2016 - Fri Apr 29 23:59:59 BST 2016 - 31

  • Sat Apr 30 00:00:00 BST 2016 - Sun May 29 23:59:59 BST 2016 - 30

  • Mon May 30 00:00:00 BST 2016 - Wed Jun 29 23:59:59 BST 2016 - 31

  • Thu Jun 30 00:00:00 BST 2016 - Fri Jul 29 23:59:59 BST 2016 - 30

  • Sat Jul 30 00:00:00 BST 2016 - Mon Aug 29 23:59:59 BST 2016 - 31

  • Tue Aug 30 00:00:00 BST 2016 - Thu Sep 29 23:59:59 BST 2016 - 31

  • Fri Sep 30 00:00:00 BST 2016 - Sat Oct 29 23:59:59 BST 2016 - 30

  • Sun Oct 30 00:00:00 BST 2016 - Tue Nov 29 23:59:59 GMT 2016 - 31

  • Wed Nov 30 00:00:00 GMT 2016 - Thu Dec 29 23:59:59 GMT 2016 - 30

  • Fri Dec 30 00:00:00 GMT 2016 - Sun Jan 29 23:59:59 GMT 2017 - 31

*/

My results are

Sat Jan 30 00:00:00 EET 2016 ::::: Sun Feb 28 23:59:59 EET 2016 ::::: 29

Mon Feb 29 00:00:00 EET 2016 ::::: Mon Mar 28 23:59:59 EEST 2016 ::::: 28

Tue Mar 29 00:00:00 EEST 2016 ::::: Thu Apr 28 23:59:59 EEST 2016 ::::: 30

Fri Apr 29 00:00:00 EEST 2016 ::::: Sat May 28 23:59:59 EEST 2016 ::::: 29

Sun May 29 00:00:00 EEST 2016 ::::: Tue Jun 28 23:59:59 EEST 2016 ::::: 30

Wed Jun 29 00:00:00 EEST 2016 ::::: Thu Jul 28 23:59:59 EEST 2016 ::::: 29

Fri Jul 29 00:00:00 EEST 2016 ::::: Sun Aug 28 23:59:59 EEST 2016 ::::: 30

Mon Aug 29 00:00:00 EEST 2016 ::::: Wed Sep 28 23:59:59 EEST 2016 ::::: 30

Thu Sep 29 00:00:00 EEST 2016 ::::: Fri Oct 28 23:59:59 EEST 2016 ::::: 29

Sat Oct 29 00:00:00 EEST 2016 ::::: Mon Nov 28 23:59:59 EET 2016 ::::: 31

Tue Nov 29 00:00:00 EET 2016 ::::: Wed Dec 28 23:59:59 EET 2016 ::::: 29

Thu Dec 29 00:00:00 EET 2016 ::::: Sat Jan 28 23:59:59 EET 2017 ::::: 30

So I’m not sure if this happens because of the February month or because 2016 was a leap year that included 29th of February.

What am I missing? I have the same problem run multiple test cases and all others are OK, but this.

I've also tried to do this with Javas 8 LocalDate and LocalDateTime and I get the exactly same results.

Here is my code

import org.apache.commons.lang.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class Main {

    public static void main(String[] args) throws ParseException {
        String startDate = "30 Jan 2016";
        String endDate = "29 Jan 2017"; // current not using this ?!
        SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");

        Date start = formatter.parse(startDate);

        List<Item> items = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            Date end = DateUtils.addMonths(start, 1);
            end = DateUtils.addSeconds(end, -1);
            items.add(new Item(start, end));
            start = DateUtils.addMonths(start, 1);
        }

        items.forEach(item -> {
            System.out.println(item.getStart() + " ::::: " + item.getEnd() + " ::::: " + getDifferenceDays(item.getStart(), item.getEnd()));
        });

    }

    public static long getDifferenceDays(Date d1, Date d2) {
        return ChronoUnit.DAYS.between(d1.toInstant(), d2.toInstant());
    }

}
  • Item Class
import java.util.Date;

public class Item {
    Date start;
    Date end;

    public Item(Date start, Date end) {
        this.start = start;
        this.end = end;
    }

    public Date getStart() {
        return start;
    }

    public void setStart(Date start) {
        this.start = start;
    }

    public Date getEnd() {
        return end;
    }

    public void setEnd(Date end) {
        this.end = end;
    }

    @Override
    public String toString() {
        return "Item{" +
                "start=" + start +
                ", end=" + end +
                '}';
    }
}
3
Well, for starters, you should not use Date, Calendar and SimpleDateFormat classes. They're troublesome. Use classes from java.time instead.MC Emperor
As I've said... I've used Javas 8 LocalDate and LocalDateTime and I get the same behavior.Palux
Did you try docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html; setting a zone. Oh I see DateUtils is an external library, recall my comment regarding it.Omar Abdel Bari
DateUtils is from import org.apache.commons.lang.time.DateUtils; I'm not getting it what exactly are you meaning by the ZonedDateTime class. Still O changed my computers date to GTM and not I'm getting the same timezones, but the date behaviour is the same.Palux
PeterMmm is correct: you're not using DateUtils correctly. But more to the point, if you're on Java 8 or higher, you're MUCH better off using the new Java "time" instead. SUGGESTION: Please try Ole V.V's advice. If it works, please "Upvote" and "Accept" it.paulsm4

3 Answers

2
votes

java.time

Since you can use java.time, the modern Java date and time API, I recommend that you stick to that and leave the old classes SimpleDateFormat and Date alone. Then you also don’t need the Apache DateUtils. The ChronoUnit enum is from java.time.

    DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("d MMM u", Locale.ENGLISH);
    
    String startDateString = "30 Jan 2016";
    LocalDate originalStartDate
            = LocalDate.parse(startDateString, dateFormatter);
    for (int i = 0; i < 12; i++) {
        LocalDate startDate = originalStartDate.plusMonths(i);
        LocalDate nextStartDate = originalStartDate.plusMonths(i + 1);
        LocalDate endDate = nextStartDate.minusDays(1);
        long differenceDays = ChronoUnit.DAYS.between(startDate, nextStartDate);
        
        System.out.format("%s - %s : %d%n", startDate, endDate, differenceDays);
    }

Output is:

2016-01-30 - 2016-02-28 : 30
2016-02-29 - 2016-03-29 : 30
2016-03-30 - 2016-04-29 : 31
2016-04-30 - 2016-05-29 : 30
2016-05-30 - 2016-06-29 : 31
2016-06-30 - 2016-07-29 : 30
2016-07-30 - 2016-08-29 : 31
2016-08-30 - 2016-09-29 : 31
2016-09-30 - 2016-10-29 : 30
2016-10-30 - 2016-11-29 : 31
2016-11-30 - 2016-12-29 : 30
2016-12-30 - 2017-01-29 : 31

What went wrong in your code?

There are a couple of reasons behind your observed unexpected results.

  1. When you add a month to January 30, you get February 29 as you had expected. In a non-leap year you would have got February 28. When you add another month to February 29, you get March 29. Is it surprising when you think about it? In a non-leap year you would have got March 28, so 2016 being a leap year actually helped you get closer to your desired result. In my code I solve this problem by adding the correct number of months to the original start date rather than adding one month to the previous start date.
  2. As PeterMmm already said, ChronoUnit.DAYS.Between() counts full 24 hours days. Any partial day is discarded. Even 23 hours 59 minutes 59 seconds. From Sat Jan 30 00:00:00 EET 2016 to Sun Feb 28 23:59:59 EET 2016 is 30 days 23 hours 59 minutes 59 seconds, so the result you get is 30 days. In my code I solve the problem by counting the days until the start of the next item.

As an aside: From Mon Feb 29 00:00:00 EET 2016 to Mon Mar 28 23:59:59 EEST 2016, because of transistion to summer time (DST) is only 28 days 22 hours 59 minutes 59 seconds. So abstaining from subtracting a second would not solve your problem in this case.

1
votes

This

end = DateUtils.addSeconds(end, -1);

isn't necessary. Or do

end = DateUtils.addSeconds(end, 0);

have a look at between() documentation. Second parameter is exclusive. That means, your second parameter does not reach the end of day and so a day less is counted (only full 24h days are counted).

1
votes

Here's a slightly different approach:

LocalDate startDate = LocalDate.of(2016, 1, 30);
LocalDate endDate = LocalDate.of(2017, 1, 30);

Function<YearMonth, LocalDate> addMonthFunction = ym -> ym
    .atDay(Math.min(startDate.getDayOfMonth(), ym.lengthOfMonth()));

long months = ChronoUnit.MONTHS.between(startDate, endDate);
YearMonth yearMonth = YearMonth.from(startDate);
Stream.iterate(yearMonth, ym -> ym.plusMonths(1))
    .limit(months)
    .map(addMonthFunction)
    .map(LocalDate::atStartOfDay)
    .map(date -> {
        LocalDateTime end = addMonthFunction.apply(YearMonth.from(date.plusMonths(1)))
            .atStartOfDay()
            .minusSeconds(1);
        long between = ChronoUnit.DAYS.between(date, end) + 1;
        return String.format("%s to %s (%s days)", date, end, between);
    })
    .forEach(System.out::println);

The idea is that each next date always falls on the 30th day of the month (or, more precisely, the same day-of-month as the start date), except if that would be an invalid date.

I used LocalDates here, but you could make it timezone-sensitive by using ZonedDateTime.