关闭

java中Calendar类的使用

标签: javaCalendar
294人阅读 评论(0) 收藏 举报
分类:
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();
		}
	}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:151372次
    • 积分:1374
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:2篇
    • 译文:0篇
    • 评论:12条
    文章分类
    最新评论