7

I am using Joda time api in a Spring 3.0 project for the very first time. Now I have a start and end date and I want to get the date for all mondays between these two dates. How can I do this ?

I have no idea where to start, can someone please advise. I looked at theis post Joda Time: How to get dates of weekdays on some date interval? and it offered some sort of guidance but its still somewhat vague due to little experience with joda.

Community
  • 1
  • 1
Faiyet
  • 5,341
  • 14
  • 51
  • 66

6 Answers6

16
LocalDate startDate = new LocalDate(2011, 11, 8);
LocalDate endDate = new LocalDate(2012, 5, 1);

LocalDate thisMonday = startDate.withDayOfWeek(DateTimeConstants.MONDAY);

if (startDate.isAfter(thisMonday)) {
    startDate = thisMonday.plusWeeks(1); // start on next monday
} else {
    startDate = thisMonday; // start on this monday
}

while (startDate.isBefore(endDate)) {
    System.out.println(startDate);
    startDate = startDate.plusWeeks(1);
}
lschin
  • 6,745
  • 2
  • 38
  • 52
  • 1
    Is there a way to calculate all days between a start and end date but skipping weekend or probably skipping saturday or sunday? – pundit Nov 17 '11 at 16:47
5

I recently developed Lamma which is designed to solve this exact use case:

Dates.from(2011, 11, 8).to(2011, 12, 30).byWeek().on(DayOfWeek.MONDAY).build();

and you will get a List<Date> of:

Date(2011,11,14)
Date(2011,11,21)
Date(2011,11,28)
Date(2011,12,5)
Date(2011,12,12)
Date(2011,12,19)
Date(2011,12,26)
Max
  • 2,065
  • 24
  • 20
4

FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

Using java.time

The LocalDate class is java.time is akin to the Joda-Time LocalDate. A date-only value, without time-of-day and without time zone. One difference is that java.time eschews constructors for factory methods.

LocalDate start = LocalDate.of( 2011 , 11 , 8 );
LocalDate stop = LocalDate.of( 2012 , 5 , 1 );

Collect the Mondays.

List<LocalDate> mondays = new ArrayList<>();

The TemporalAdjuster interface provides for classes that manipulate date-time values. The TemporalAdjusters class (note the plural name) provides various implementations. We want the nextOrSame and next adjusters, passing the desired DayOfWeek.MONDAY enum object.

LocalDate monday = start.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) );
while( monday.isBefore( stop ) ) {
    mondays.add( monday );
    // Set up the next loop.
    monday = monday.plusWeeks( 1 );
}

By the way, usually the wise approach in handling a span of time is Half-Open where the beginning is inclusive while the ending is exclusive. So in the code above we are running up to, but not including, the stop date.

If the ending is inclusive, use the negation of isAfter e.g.

while( !monday.isAfter( stop ) ) {
    //...
}

Here, monday is not after stop means it is before or up to stop.


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.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

This code takes to string dates and gives the number of sundays and also all the sunday's dates

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

public class FindAllSundays {


public static int getNumberofSundays(String d1, String d2) throws Exception { // object
                                                                                // in
                                                                                // Date
                                                                                // form

    Date date1 = getDate(d1);
    Date date2 = getDate(d2);

    Calendar c1 = Calendar.getInstance();
    c1.setTime(date1);
    Calendar c2 = Calendar.getInstance();
    c2.setTime(date2);
    int sundays = 0;
    while (c2.after(c1)) {
        // System.out.println(" came here ");
        //checks to see if the day1 ....so on next days are sundays if sunday goes inside to increment the counter
        if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            System.out.println(c1.getTime().toString() + " is a sunday ");
            sundays++;

        }
        c1.add(Calendar.DATE, 1);
    }

    System.out.println("number of sundays between 2 dates is " + sundays);

    return sundays;
}
// converts string to date 
public static Date getDate(String s) {
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;
    try {
        date = format.parse(s);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date;
}

public static void main(String[] arg) throws Exception {
    System.out.println(" " + getNumberofSundays("2005-10-07", "2006-10-01"));
}

}

Vivek
  • 31
  • 4
1
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class Get_time {

    public  ArrayList<LocalDate> getmondays(String s,String e)
    {
        LocalDate start = LocalDate.parse(s);
        LocalDate end = LocalDate.parse(e);
        List<LocalDate> totalDates_Mondays = new ArrayList<>();

        while (!start.isAfter(end)) {
            totalDates_Mondays.add(start);
            start = start.plusWeeks(1);
        }
        return (ArrayList<LocalDate>) totalDates_Mondays;
    }

    public static void main(String ...s1) {

        String mon_start = "1600-08-01";
        String mon_end= "2016-12-29";
        Get_time t=new Get_time();
        System.out.println(t.getmondays(mon_start,mon_end));
    }
}
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
0

In Java 8 using Stream ,

LocalDate startDate = LocalDate.of(2019, 2, 1);
LocalDate endDate = LocalDate.of(2019, 2, 28);
long numOfDays = ChronoUnit.DAYS.between(startDate, endDate);
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).filter( date -> date.getDayOfWeek()==DayOfWeek.MONDAY ).collect(Collectors.toList());
Saurabh
  • 7,525
  • 4
  • 45
  • 46