java:如何获取一周、一月、一年的第一天和最后一天

先说一年。

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值