2

I want my app to parse the date in format "dd-MMM-yyyy". The date has been successfully parsed when I try to get month and get year it is giving other result. I inpued 06-sep-2014 as date. But when I try to extract month and year from the parsed date it is showing 8 for month instead of 9 and 114 for year instead of 2014.

logcat output

6

8

114

Here's my code

    String date1 = "06 sep 2014";
    SimpleDateFormat format1 = new SimpleDateFormat("dd MMM yyyy");
    SimpleDateFormat format2 = new SimpleDateFormat("d MMM yyyy");

    Date date;

    try {
        if (date1.length() == 11) {
            date = format1.parse(date1);

        } else {
            date = format2.parse(date1);

        }
        int day=date.getDate();
        int  mon1=date.getMonth();
        int year1=date.getYear();

        System.out.println("date is:"+ date);

        System.out.println(day);
        System.out.println(mon1);
        System.out.println(year1);


    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

3 Answers3

4
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public final class DateParseDemo {
    public static void main(String[] args){
         final DateFormat df = new SimpleDateFormat("dd MMM yyyy");
         final Calendar c = Calendar.getInstance();
         try {
             c.setTime(df.parse("06 sep 2014"));
             System.out.println("Year = " + c.get(Calendar.YEAR));
             System.out.println("Month = " + (c.get(Calendar.MONTH)));
             System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
         } 
         catch (ParseException e) {
             e.printStackTrace();
         }
    }
}

Output:

  • Year = 2014
  • Month = 8
  • Day = 6

And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,

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

Suhail Mehta
  • 5,514
  • 2
  • 23
  • 37
3

Because date.getyear Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

Maybe, You can use for example;

int year1=date.getYear();
System.out.println(year1+1900);

Tarık Yurtlu
  • 1,160
  • 1
  • 8
  • 12
0

Using the Date class, it gives you the year starting from 1900. A better way to get what you want is using the Calendar class. See http://developer.android.com/reference/java/util/Date.html#getYear()