-1

I need to prepare a list of week day dates

Note :- Week day are not satudrday or sunday, (I can pass the Week day as parameter)

I have written following code but not working, Can you please correct the code

public static void main (String[] args) {

  List weekoffDates = new ArrayList<Timestamp>();
  Timestamp date = "2013-12-01 00:00:00.0"; //This is timestamp object not string
  Timestamp endDate = "2013-12-31 00:00:00.0"; //This is timestamp object not string
  int dayOfWeek  = 3 //TuesDay

  for ( int i =1 ; i<=5; i++ ) {
    if( ! date.after(endDate) ) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(date.getTime());
        calendar.set( Calendar.DAY_OF_WEEK, dayOfWeek  );  //This is my parameter
        //calendar.set( Calendar.WEEK_OF_MONTH, i );        
        date = new Timestamp( calendar.getTimeInMillis() );
        weekoffDates.add(date); 
        dayOfWeek = dayOfWeek +7;
        System.out.println(date);
    }
    System.out.println(weekoffDates);  
  }
}

EDIT:-
date :- 2013:December:1 (I have sent as Timestamp object)
EndDate :- 2013:December:31 (I have sent as Timestamp object)
dayOfWeek :- This is Day Of Week ( I have sent this parameter as tuesday 3 ) //It will change dynamically
Expected Result :-
All tuesday in the month of decemer as ArrayListlist
Problem :- calendar.set( Calendar.DAY_OF_WEEK, dayOfWeek ); setting is wrong

Giri
  • 507
  • 6
  • 23
  • 1
    No, It was not giving the expected results For example 2013 december 1 as the date and endDate is 31 december 2013 And tuesday as the week off day – Giri Dec 29 '13 at 08:38
  • 1
    Please post a short but *complete* program demonstrating the problem, as well as expected and actual results. I'd also strongly advise you to consider using Joda Time as a much better date/time API. – Jon Skeet Dec 29 '13 at 08:38
  • Thanks jon, I thought it is very simple requirement and i can achieve with the java calendar and Timestamp.I will surely i update the question with my previous comment – Giri Dec 29 '13 at 08:40
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 08 '17 at 19:07

3 Answers3

2

You would have to iterate over the days between start and end days. Within the iterating loop, you can check for the day your need to store and then store it in your list.

Below is a crude working example which you can modify according to your best practices or different data types which you might want to use:

public static void main(String[] args) {
        List<String> workDays = new ArrayList<String>();
        int dayOfWeek  = 3; //TuesDay

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        startDate.set(2013, 11, 1);
        endDate.set(2013, 11, 31);

        while (startDate.getTimeInMillis() <= endDate.getTimeInMillis()) {
            if (startDate.get(Calendar.DAY_OF_WEEK) == dayOfWeek) {
                workDays.add(startDate.getTime().toString());
                System.out.println(startDate.getTime());
            }
            startDate.add(Calendar.DAY_OF_MONTH, 1);
        }


    }

Note the hardcoded start and end dates have month parameter as 11 for Deember, since January = 0 under java.util.Calendar

StoopidDonut
  • 8,547
  • 2
  • 33
  • 51
1

java.time

The modern approach uses the java.time classes rather than troublesome legacy classes such as Date & Calendar.

You seem to be asking for a sequence of dates for the same day-of-week within a particular month. So you need not iterate all the individual dates as we know they are exactly seven days apart. You need only find the first date with the desired day-of-week, then add a week at a time.

The LocalDate class represents a date-only value without time-of-day and without time zone.

DayOfWeek dow = DayOfWeek.WEDNESDAY ;
YearMonth ym = YearMonth.of( 2013 , Month.DECEMBER ) ;

LocalDate firstOfMonth = ym.atDay( 1 );
LocalDate firstDowOfMonth = firstOfMonth.with( TemporalAdjusters.nextOrSame( dow ) ) ;

List< LocalDate > dates = new ArrayList<>( 5 );   // A month has a maximum of five occurrences of a day-of-week.
LocalDate ld = firstDowOfMonth ;
do {
    dates.add( ld ) ;
    // Set up the next loop.
    ld = ld.plusWeeks( 1 );
} while ( YearMonth.from( ld ).equals( ym ) ) ;  // Continue while in the desired month.

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.

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

I have updated above (I have mentioned in question) code as below.
This code snippet also giving proper results. (Here no need to iterate all the dates of a month)

public static void main(String[] args) {

      List weekoffDates = new ArrayList<Timestamp>();
      Timestamp fromDate = getTimestamp(2013, 12, 1);
      Timestamp endDate  = getTimestamp(2013, 12, 31);
      int dayOfWeek  = 4; //Wednes Day
      int maxWeeksInAMonth  =   5;
      Timestamp tempDate    =   fromDate;
        for ( int i =1 ; i<=maxWeeksInAMonth; i++ ) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(fromDate.getTime());
            calendar.set( Calendar.DAY_OF_WEEK, dayOfWeek  );
            calendar.set( Calendar.WEEK_OF_MONTH, i );
            tempDate = new Timestamp( calendar.getTimeInMillis() );
            if ( ( tempDate.compareTo(endDate) <= 0 ) 
                         && ( tempDate.compareTo(fromDate) >=0 ) )  {
                weekoffDates.add(tempDate); 
                System.out.println(tempDate);
            }
        }
        System.out.println(weekoffDates);
} // main

static Timestamp getTimestamp(int year, int month, int day) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month - 1, day);
    return new Timestamp(cal.getTimeInMillis());
} // getTimestamp
Giri
  • 507
  • 6
  • 23