日期:2014-05-20  浏览次数:20798 次

日历类插入时间日期的问题,月份比实际少一个月
Calendar calendar = Calendar.getInstance();//创建日历对象
String date_and_time = calendar.get(Calendar.YEAR) + "年" + /*年*/
  calendar.get(Calendar.MONTH)+ "月" + /*月*/
  calendar.get(Calendar.DAY_OF_MONTH)+ "日" + /*日*/
  calendar.get(Calendar.HOUR_OF_DAY) + ":" /*时*/
  + calendar.get(Calendar.MINUTE) + ":" /*分*/
  + calendar.get(Calendar.SECOND); /*秒*/



System.out.println(date_and_time);


  比如实际日期是2012年7月23日 13:54:35
  运行变成 2012年6月23日 13:54:35 .

少一个月。虽然可以加1实现,我就想问为什么

------解决方案--------------------
calendar.get(Calendar.MONTH)
如果是1月,返回的是0。它下标从0开始,所以转到实际的要加1。

下面这段代码,就看出来了,如果是12月,c.get(Calendar.MONTH)返回的是11。

String s = "20121201";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = sdf.parse(s);
Calendar c = Calendar.getInstance();
c.setTime(date);

System.out.println(c.get(Calendar.MONTH));
------解决方案--------------------
探讨
比如实际日期是2012年7月23日 13:54:35
运行变成 2012年6月23日 13:54:35 .

少一个月。虽然可以加1实现,我就想问为什么

------解决方案--------------------
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year is JANUARY which is 0; the last depends on the number of months in a year.

注意红色的部分,Calendar的月份是从0开始计算的,0代表January,以此类推6代表July即我们的7月份。
good~