solidfox
solidfox

Reputation: 571

Converting Date to Calendar issues

Today is 2013-02-25, but why this code returns 2013-03-25?

       String currentDate =  new SimpleDateFormat("yyyy MM dd hh mm ss").format(new java.util.Date());
       System.out.println("current Date "+currentDate);
       StringTokenizer  token = new StringTokenizer(currentDate);
       Calendar cal = Calendar.getInstance();
       cal.set(Integer.parseInt(token.nextToken()),
               Integer.parseInt(token.nextToken()), 
               Integer.parseInt(token.nextToken()), 
               Integer.parseInt(token.nextToken()),
               Integer.parseInt(token.nextToken()),
               Integer.parseInt(token.nextToken()));
       String calenderDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
       System.out.println("calender date "+calenderDate);
       cal.add(Calendar.MONTH, -1); //  set to one month ago
       String pastDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cal.getTime());
       System.out.println("past Date "+pastDate);

out put

current Date 2013 02 25 04 56 26

calender date 2013-03-25 04:56:26

past Date 2013-02-25 04:56:26

Upvotes: 1

Views: 190

Answers (3)

Christophe Roussy
Christophe Roussy

Reputation: 17049

Calendar months start at 0, see JavaDoc:

@param month the value used to set the MONTH calendar field. * Month value is 0-based. e.g., 0 for January.

This is a royal PITA and most Java developers lost some time on that one, it certainly violates the principle of least surprise. Be very careful when using the Calendar class... There are alternatives like Joda time.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1075537

In the JDK, month values start with 0. So 2 = March.

From the Calendar#set docs:

month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

Upvotes: 3

Alberto Segura
Alberto Segura

Reputation: 755

Subtract one to the month. So it works the API. I.e.:

month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

Upvotes: 5

Related Questions