0

July 1, 2010 corresponds to a Thursday, how do I get the value of Thursday programmatically.

Evernoob
  • 5,551
  • 8
  • 37
  • 49
user339108
  • 12,613
  • 33
  • 81
  • 112

4 Answers4

10
Calendar day= new GregorianCalendar(2010, Calendar.JULY, 1);
int dayOfWeek = day.get(Calendar.DAY_OF_WEEK); // 5=Thursday
pauljwilliams
  • 19,079
  • 3
  • 51
  • 79
0
public static Date shiftDayOfWeekinMonth(Date input, int monthsToAdd) {

Calendar cal = Calendar.getInstance();
cal.setTime(input);

int dayOfWeekInMonth = cal.get(GregorianCalendar.DAY_OF_WEEK_IN_MONTH);
int month = cal.get(GregorianCalendar.MONTH);

// month increment
cal.add(GregorianCalendar.MONTH, monthsToAdd);
// sets the day of week in month
cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, dayOfWeekInMonth);

//overflow month control
int currentMonthIndex = (month + monthsToAdd) % 12;
if (currentMonthIndex != cal.get(GregorianCalendar.MONTH)) {
    cal.add(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
}

return cal.getTime();
}

using this method to get any days of week in month for each month starting by an input date.

giaffa86
  • 708
  • 1
  • 9
  • 22
0

Joda-Time

Using the Joda-Time 2.5 library rather than the notoriously troublesome java.util.Date and .Calendar classes.

Day of week numbers are define by the ISO 8601 standard. Monday is one, Sunday is seven.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime firstOfMonth = DateTime.now( zone ).withDayOfMonth( 1 ).withTimeAtStartOfDay();
int dayOfWeekNumber = firstOfMonth.getDayOfWeek(); 
String dayName = DateTimeFormat.forPattern( "EEEE" ).withLocale( Locale.CANADA_FRENCH ).print( firstOfMonth );  
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Use below method by Passing year and month as parameters

private String getFirstWeekOfTheMonth(int year, int month){
    String weeks[] = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thusday", "Friday", "Sunday"};
    Calendar calender = Calendar.getInstance();
    calender.set(year, month, 1);
    return weeks[calender.get(Calendar.DAY_OF_WEEK)-1];
}

Example:-

String currentWeek = getFirstWeekOfTheMonth(2010, Calendar.JULY);

here currentWeek is Thursday

sandeepmaaram
  • 4,191
  • 2
  • 37
  • 42