码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-06-13 17:02:24      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:java   get   string      for   时间   

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

Java Calendar获取年、月、日、时间,布布扣,bubuko.com

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

标签:java   get   string      for   时间   

原文地址:http://www.cnblogs.com/lpjia/p/3784649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!