时间:2010-07-26 09:06:26

标签: java

4 个答案:

答案 0 :(得分:10)

答案 1 :(得分: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();
}

使用此方法从输入日期开始,每个月获得一周中的任何一天。

答案 2 :(得分:0)

约达时间

使用Joda-Time 2.5库而不是臭名昭着的java.util.Date和.Calendar类。

星期几数字由ISO 8601标准定义。周一是一个,周日是七个。

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

答案 3 :(得分:0)

使用以下方法将年份和月份作为参数传递

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];
}

示例: -

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

这里currentWeek 星期四