获得当前月份的月初和月末

	/**方法	获得月初月末,算法思路
     *
     *月初的日字段设为1,得到月初
     *月份先加一个月,得到下个月
	 *在此基础上-1天,即日字段设为 1-1 = 0,得到本月月末
     *
     *此处Java容错性强大,一般日期设置不正常也不会错,会自动调整
	 * 
	 */
	@Test
	public void getMonthFirstAndEnd(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Calendar currentMonth = Calendar.getInstance();
		currentMonth.set(currentMonth.get(Calendar.YEAR), currentMonth.get(Calendar.MONTH), 1);
		
		String time = sdf.format(currentMonth.getTime().getTime());
		System.out.println(time);//这说明currentMonth.get(Calendar.MONTH)等于人类标准的当前月份-1
		
		currentMonth.set(currentMonth.get(Calendar.YEAR), currentMonth.get(Calendar.MONTH) + 1, 0);
		time = sdf.format(currentMonth.getTime().getTime());
		System.out.println(time);
	}

测试结果

2018-08-01 15:53:45
2018-08-31 15:53:45


版权声明:本文为u013301376原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。