tags:

views:

779

answers:

7

am seriously looking for this code...am now to programing

actually i want to make all dates with flag,which all are sunday in a particulr year.plz am eagarly waiting for ur response....

+5  A: 

Study the the docs of java.util.Calendar carefully.

starblue
A: 

A year has approximately 365 days, so the Big-O's n is pretty manageable. I'd say just iterate from the beginning of the year through to the last day of the year, and check if each day is a Sunday or not.

You need at least Calendar.get(), Calendar.DAY_OF_WEEK and Calendar.SUNDAY

Henrik Paul
A year has 365 days (even if its approx :-))
Vijay Dev
good point, thanks for the correction :)
Henrik Paul
+8  A: 

Create a new calendar. Set the time to 1/1/yyyy and some time. Check if the current date is a Sunday and roll forward one day until it is. That's the first Sunday of the year. Roll forward 7 days until the year no longer matches, marking as you go.

tvanfosson
+1: If he can't get it from that description, he's got more than just one problem.
Michael Myers
+3  A: 

If i was doing it I would use Joda Time to find the first Sunday in the year using LocalDate. Create 1st of Jan and then add 1 day until it is a Sunday, then add 7 days until your run out of year.

LocalDate date = new LocalDate(YEAR, 1, 1);
while ( date.dayOfWeek() != 7 )
{
  date = date.addDays(1);
}

while ( date.year() == YEAR )
{
  date = date.addDays(7);
}

Or something like that.

TiGz
A: 

Something like this should work.

int year = 2009;
Calendar cal = new GregorianCalendar(year, Calendar.JANUARY, 1);
for (int i = 0, inc = 1; i < 366 && cal.get(Calendar.YEAR) == year; i+=inc) {
    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
        // this is a sunday
        cal.add(Calendar.DAY_OF_MONTH, 7); 
        inc = 7;
    } else {
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
Miles D
+1  A: 

This is an example code using java.util.Calendar and java.util.GregorianCalendar that prints out each Sunday of the year 2009. A lot of optimizing can be done in formatting the date, but i'll leave that as an exercise for you.

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Test
{
    public static void main(String[] args)
    {
     int year =2009;
     int dayOfWeek = Calendar.SUNDAY;
     String dayOfWeekString = "Sunday";
     // instantiate Calender and set to first Sunday of 2009
     Calendar cal = new GregorianCalendar();
     cal.set(2009, 0, 1, 0, 0); cal.getTime();
     cal.set(Calendar.DAY_OF_WEEK, dayOfWeek); cal.getTime();
     int i = 1;
     while (cal.get(Calendar.YEAR) == 2009)
     {
      System.out.println(dayOfWeekString + " " + i + ": " + cal);
      cal.add(Calendar.DAY_OF_MONTH, 7);
      i++;
     }
    }
}

As you can see, TiGz's way of using Joda Time is a lot simpler.

tehvan
A: 

Yah this is Subbu....

Thanks a million to one and all...and i love very much StackOverFlow .... Hats Up to all