Smitha
Smitha

Reputation: 6134

Problem with converting string to Calendar date in android

I have the following program but it wrongly displays the month. please help.

        date1="31/12/2011";  
                SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");   
        try {    
            d1 = (Date)formatter.parse(date1);  
             System.out.println("dateeeeeeeeeeeeeeee " + date1);  

            tdy1=Calendar.getInstance();  
            System.out.println("tdy mnthhhhhhhhhhh " + tdy1.get(Calendar.MONTH));  
            tdy1.setTime(d1);  

        System.out.println("Month of date1= " + tdy1.get(Calendar.MONTH));    
        //catch exception 
    } catch (ParseException e) {   
            // TODO Auto-generated catch block  
            e.printStackTrace();   
        }   

And out put is :
Month of date1= 0 Wat might be the problem??

Upvotes: 2

Views: 11681

Answers (2)

Niranj Patel
Niranj Patel

Reputation: 33238

Try below code

    String date1 = "31/12/2011";
    SimpleDateFormat form = new SimpleDateFormat("dd/MM/yyyy");
    java.util.Date d1 = null;
    Calendar tdy1;

    try {
        d1 = form.parse(date1);
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    tdy1 = Calendar.getInstance();
    System.out.println("tdy mnthhhhhhhhhhh " + tdy1.get(Calendar.MONTH));
    tdy1.setTime(d1);

    System.out.println("Month of date1= " + tdy1.get(Calendar.MONTH));

Note" Calendar.MONTH is return integer value and it is start from 0 to 11 means 0=JANUARY and 11=DECEMBER

for more detail check Calendar

Upvotes: 16

MatF
MatF

Reputation: 1736

Your SimpleDateFormat is initialized wrong. Small m is for minutes of hour. You are looking for big M, Month of Year. http://download.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Upvotes: 5

Related Questions