首页 > 代码库 > Java Calendar获取年、月、日、时间

Java Calendar获取年、月、日、时间

Java Calendar获取年、月、日、时间

  Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));    //获取东八区时间

  int year = c.get(Calendar.YEAR);    //获取年
  int month = c.get(Calendar.MONTH) + 1;   //获取月份,0表示1月份
  int day = c.get(Calendar.DAY_OF_MONTH);    //获取当前天数
  int first = c.getActualMinimum(c.DAY_OF_MONTH);    //获取本月最小天数
  int last = c.getActualMaximum(c.DAY_OF_MONTH);    //获取本月最大天数
  int time = c.get(Calendar.HOUR_OF_DAY);       //获取当前小时
  int min = c.get(Calendar.MINUTE);          //获取当前分钟
  int xx = c.get(Calendar.SECOND);          //获取当前秒

  SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  String curDate = s.format(c.getTime());  //当前日期
  System.out.println("当前时间:"+year + "-" + month + "-"+ day + " "+time + ":" + min +":" + xx);
  System.out.println("第一天和最后天:" + first +"," + last);

  System.out.println("当前日期curDate====:" + curDate);

输出结果:

当前时间:2012-9-25 22:50:54
第一天和最后天:1,30

当前日期curDate:2012-09-25 22:50:54

Calendar的计算

  c.add(Calendar.YEAR, 1);
  c.add(Calendar.MONTH, 1);
  c.add(Calendar.DAY_OF_MONTH, 1);
  int year2 = c.get(Calendar.YEAR);
  int month2 = c.get(Calendar.MONTH) + 1;
  int day2 = c.get(Calendar.DAY_OF_MONTH);
  int firstD = c.getActualMinimum(c.DAY_OF_MONTH);
  int lastD = c.getActualMaximum(c.DAY_OF_MONTH);
  System.out.println("当前时间:"+year2 + "-" + month2 + "-"+ day2 + " "+time + ":" + min +":" + xx);
  System.out.println("第一天和最后天:" + firstD +"," + lastD);

输出结果:

当前时间:2013-10-26 23:4:3
第一天和最后天:1,31

获取上个月的年、月、日

Calendar c=Calendar.getInstance();

c.add(Calendar.MONTH, -1);//上个月

SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String year=String.valueOf(c.get(Calendar.YEAR));

String topDay = String.valueOf(c.getActualMinimum(Calendar.DAY_OF_MONTH));

String lastDay = String.valueOf(c.getActualMaximum(Calendar.DAY_OF_MONTH)); 

//上个月

String lastMonth=String.valueOf(c.get(Calendar.MONTH)+1).length()==2?String.valueOf(c.get(Calendar.MONTH)+1):"0"+String.valueOf(c.get(Calendar.MONTH)+1);

String topDayMonth=year+"-"+lastMonth+"-"+"01" + " 00:00:00";

String lastDayMonth = year+"-"+lastMonth+"-"+lastDay+ " 23:59:59";

System.out.println("###year:" + year);

System.out.println("###last month:" + lastMonth);

        System.out.println("###topday:" + topDayMonth);

        System.out.println("###lastday:" + lastDayMonth);

输出结果

###year:2013

###last month:04

###topday:2013-04-01 00:00:00

###lastday:2013-04-30 23:59:59