java中Calendar类的使用

public class TestCalendar {

	@Test
	public void test(){
		try {
			Calendar calendar = new GregorianCalendar();//子类实例化
			//获取年、月、日、时、分、秒、毫秒
			System.out.println("年: "+calendar.get(Calendar.YEAR));
			System.out.println("月 "+(calendar.get(Calendar.MONTH)+1));
			System.out.println("日: "+calendar.get(Calendar.DAY_OF_MONTH));
			System.out.println("时: "+calendar.get(Calendar.HOUR_OF_DAY));
			System.out.println("分: "+calendar.get(Calendar.MINUTE));
			System.out.println("秒: "+calendar.get(Calendar.SECOND));
			System.out.println("毫秒 "+calendar.get(Calendar.MILLISECOND));
			
			// 当前月第一天、最后一天
			int currYear = calendar.get(Calendar.YEAR);
			int currMonth = calendar.get(Calendar.MONTH) + 1;
			System.out.print(currYear + "-" + currMonth);
			SimpleDateFormat datef = new SimpleDateFormat("yyyy-MM-dd");
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			Date beginTime = calendar.getTime();
			String sTime = datef.format(beginTime) + " 00:00:00";
			calendar.set(Calendar.DATE, 1);
			calendar.roll(Calendar.DATE, -1);
			Date endTime = calendar.getTime();
			String eTime = datef.format(endTime) + " 23:59:59";
			System.out.println("第一天"+sTime+"最后一天"+eTime);
			
			Calendar cal = Calendar.getInstance(); 
			//指定年月的的第一天、最后一天
			int year = 2015;
			int moth = 3;
			cal.set(Calendar.YEAR,year);
			cal.set(Calendar.MONTH, moth-1);
			//当前月的最后一天   
			cal.set( Calendar.DATE, 1 );
			cal.roll(Calendar.DATE, - 1 );
			Date endTime2=cal.getTime();
			String endTimeStr=datef.format(endTime2)+" 23:59:59";
			//当前月的第一天          
			cal.set(GregorianCalendar.DAY_OF_MONTH, 1); 
			Date beginTime2=cal.getTime();
			String beginTimeStr=datef.format(beginTime2)+" 00:00:00";
			
			System.out.println("指定年月的的第一天"+endTimeStr+"最后一天"+beginTimeStr);
			
			//当前时间的前一天
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd:HH");  
			String tmStr = "2015-5-18:00";
			Date d = sdf2.parse(tmStr);  
			System.out.println(d);
			Calendar now = Calendar.getInstance();  
			now.setTime(d);  
			now.set(Calendar.HOUR, now.get(Calendar.HOUR) -1);  
			System.out.println(sdf2.format(now.getTime()));
			
			//最近N天
			SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			cal.add(Calendar.DATE,-7);
			System.out.println("最近7天"+df2.format(cal.getTime()));
			Calendar ca2 =Calendar.getInstance();
			//最近N个月
			ca2.add(Calendar.MONTH,-1);//最近一个月
			System.out.println("最近一个月"+df2.format(ca2.getTime()));
			Calendar ca3 =Calendar.getInstance();
			//最近N个年
			ca3.add(Calendar.YEAR,-1);//最近一年
			System.out.println("最近一年"+df2.format(ca3.getTime()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tanksyg/article/details/49925339
文章标签: java Calendar
个人分类: java
上一篇MySQL查看和修改最大连接数
下一篇java通过反射Method、属性字段名、值、数据类型
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭