Devrath
Devrath

Reputation: 42854

Is there a way to get the days as a result of arrays if we pass two dates into a function in java

How to get different days between two dates in java:

Source Date: 01-09-2015

Destination Date: 03-09-2015 .

So there are three days: Tuesday, Wednesday, Thursday but does not include Monday, Friday, Saturday, Sunday


Question:

  1. Is there a way to get the days as a result of arrays if we pass two dates into a function in java
  2. Also trying not to have duplicate values(Monday-Sunday)

Upvotes: 0

Views: 109

Answers (2)

akhil_mittal
akhil_mittal

Reputation: 24167

I have quickly compiled the following program in Java which may serve your purpose.

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
        String inputString1 = "01-09-2015";
        String inputString2 = "10-09-2015";
        Date date1 = myFormat.parse(inputString1);
        Date date2 = myFormat.parse(inputString2);
        long diff = date2.getTime() - date1.getTime();
        Calendar c = Calendar.getInstance();
        c.setTime(date1);


        int days = (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
        days = Math.min(days,7);
        String[] resultArray = new String[days];
        for(int i=0; i< days; i++) {
            c.add(Calendar.DATE, 1);
            String result = new SimpleDateFormat("EE").format(c.getTime());
            resultArray[i] = result;
        }
        System.out.println(Arrays.toString(resultArray));
        }

It prints:

[Wed, Thu, Fri, Sat, Sun, Mon, Tue]

Upvotes: 1

Matthieu Nogueron
Matthieu Nogueron

Reputation: 54

Using Joda Time, you can do like this :

public ArrayList<String> getDaysBetween(String start, String end){
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
    DateTime dstart = formatter.parseDateTime(start);
    DateTime dend = formatter.parseDateTime(end);

    ArrayList<String> days = new ArrayList<>();
    while (dstart.getDayOfYear() <= dend.getDayOfYear()){
        String day = dstart.dayOfWeek().getAsText();
        if(!days.contains(day)){
            days.add(day);
        }
        dstart = dstart.plusDays(1);
    }
    return days;
}

It works when the two dates are on the same year.

Moreover:

dstart.dayOfWeek().getAsText();

return a String based on the current local (in French : "mardi", "mercredi"... - in English : "tuesday", "wednesday"...).

Upvotes: 0

Related Questions