先说一年。
public static Calendar getFirstDayOfYear(Calendar c)
{
c.set(Calendar.DAY_OF_YEAR,1);
return c;
}
public static Calendar getLastDayOfYear(Calendar c)
{
c.set(Calendar.DAY_OF_YEAR,1);
c.add(Calendar.DAY_OF_YEAR,-1);
c.add(Calendar.YEAR,1);
return c;
}
一月的第一天和最后一天
public static Calendar getFirstDayOfMonth(Calendar c)
{
c.set(Calendar.DAY_OF_MONTH, 1);
return c;
}
public static Calendar getLastDayOfMonth(Calendar c)
{
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.MONTH, 1);
c.add(Calendar.DAY_OF_YEAR, -1);
return c;
}
一周的第一天和最后一天。需要注意的一个问题是一周的开始和结束在不同的地区是不一样的。
public static Calendar getFirstDayOfWeek(Calendar c)
{
c.set(Calendar.DAY_OF_WEEK, 1);
return c;
}
public static Calendar getLastDayOfWeek(Calendar c)
{
c.set(Calendar.DAY_OF_WEEK, 1);
c.add(Calendar.DAY_OF_YEAR, 6);
return c;
}
如果一周的开始时间是固定的,那么,要用下面的方法来获取一周的第一天和最后一天:
public static Calendar getFirstDayOfWeek(Calendar x)
{
boolean isFirstSunday = (x.getFirstDayOfWeek() == Calendar.SUNDAY);
int weekDay = x.get(Calendar.DAY_OF_WEEK);
if (isFirstSunday)
{
weekDay = weekDay - 1;
if (weekDay == 0)
{
weekDay = 7;
}
}
x.add(Calendar.DAY_OF_YEAR, (-1) * (weekDay - 1));
return x;
}
public static Calendar getLastDayOfWeek(Calendar x)
{
boolean isFirstSunday = (x.getFirstDayOfWeek() == Calendar.SUNDAY);
int weekDay = x.get(Calendar.DAY_OF_WEEK);
if (isFirstSunday)
{
weekDay = weekDay - 1;
if (weekDay == 0)
{
weekDay = 7;
}
}
x.add(Calendar.DAY_OF_YEAR, 7 - weekDay);
return x;
}