开发者

How tdo I get the day of the week, of the first day of the month? [duplicate]

This question already has answers here: How to get the first day of the current week and month? 开发者_如何转开发 (15 answers) Closed 8 years ago.

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


Calendar day= new GregorianCalendar(2010, Calendar.JULY, 1);
int dayOfWeek = day.get(Calendar.DAY_OF_WEEK); // 5=Thursday


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.


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 );  


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜