在java中无法将1月增加1

时间:2016-07-11 08:07:07

标签: java date calendar

我必须从当前日期开始在mysql db中存储接下来30天的日期。如果月份到达终点,它应该自动开始从nxt月份开始。当我以类似的格式存储日期时,这种情况正常发生 “Mon Jul 11​​ 13:28:23 IST 2016”。它正是这样发生的。

Calendar calendar = Calendar.getInstance();
if(repetitionSpan.equals("weekly")){
        for(int i=0;i<7;i++){               
            String insertQuery="insert into notifications(notificationId,messageForUser,notificationReceiver,notificationSender,status,timeOfNotification,typeOfNotification)values('"+"RM"+calendar.getTimeInMillis()+"','"+notificationDetails.getMessageForUser()+"','"+notificationDetails.getNotificationReceiver()+"','"+notificationDetails.getNotificationSender()+"','"+notificationDetails.getStatus()+"','"+calendar.getTime()+"','"+notificationDetails.getTypeOfNotification()+"')";
            sessionFactory.getCurrentSession().createSQLQuery(insertQuery).executeUpdate(); 
            calendar.add(Calendar.DATE, 1);
        }

在可爱的情况下它运作良好。但在另一种情况下,我以“yyyy / mm / dd”格式存储日期,它无效。

String DATE_FORMAT = "yyyy/mm/dd";
String date_string = "2001/08/12";
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat(DATE_FORMAT);
Date date = (Date)sdf.parse(date_string);
Calendar c1 = Calendar.getInstance();
c1.setTime(date); 
int maxDay = c1.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("maxDay is"+maxDay);
System.out.println("last month date is"+c1.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println("Date is : " + sdf.format(c1.getTime()));
for(int i=0;i<maxDay;i++){
    c1.add(Calendar.DATE,1);
    System.out.println("Date + 1 month is : " + sdf.format(c1.getTime()));
}

输出为: - 月份没有增加(即使在日期达到31之后)

1 个答案:

答案 0 :(得分:4)

您的问题是格式。

String DATE_FORMAT = "yyyy/mm/dd";

mm表示

  

分钟小时

因此,为了获得正确的Date,您必须使用:

String DATE_FORMAT = "yyyy/MM/dd";

<强>输出:

maxDay is31
last month date is31
Date is : 2001/08/12
Date + 1 month is : 2001/08/13
Date + 1 month is : 2001/08/14
Date + 1 month is : 2001/08/15
Date + 1 month is : 2001/08/16
Date + 1 month is : 2001/08/17
Date + 1 month is : 2001/08/18
Date + 1 month is : 2001/08/19
.....
Date + 1 month is : 2001/09/11
Date + 1 month is : 2001/09/12

WORKING IDEONE DEMO!