Benji Weiss
Benji Weiss

Reputation: 416

java.text.ParseException Unparsable Date: "0"

Im trying to convert a string

2010-03-09

into a date, to furthermore get the Day of year.

String dt = "2010-03-09";
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new GregorianCalendar();
Date d = date.parse(dt);
cal.setTime(d);
int doy = cal.get(Calendar.DAY_OF_YEAR); 

Im not sure why i get this error

Exception in thread "main" java.text.ParseException: Unparseable date: "0"

Is there something wrong with the SimpleDateFormat string pattern as my parameter?

My conditions are strict with the string being the format of

2010-03-09

Bc i have an array of 4000 dates in this format

Any help would be kindly appreciated, Im new to the Calendar, Date and SimpleDateFormat Classes

I am dealing with arrays, the example above is a general case. here is the actual case i am dealing with

public static int[] todoy(String[] dt) {        // input array of String (dates) and will return array of DOY's
    int[] re = new int[size];
    Date d = null;
    for (int i=0;i<size;i++){
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = new GregorianCalendar();
        try {
            d = date.parse(dt[i]);
        } catch (ParseException e) {
                e.printStackTrace();
        }
        cal.setTime(d);
        re[i] = cal.get(Calendar.DAY_OF_YEAR); 

    }//fill in array of DOY's 
    return re;
}//inputs date such as 5/2 and returns integer for which day of the year it is

Upvotes: 1

Views: 1161

Answers (1)

akhil_mittal
akhil_mittal

Reputation: 24177

Can you please try this code?

  public static int[] todoy(String[] dt) {        // input array of String (dates) and will return array of DOY's
    int[] re = new int[size];
    Date d = null;
    if(dt == null) return null;

    for (int i=0;i<size;i++){
        if(dt[i] != null && dt[i] != "0") {
            SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = new GregorianCalendar();
            try {
                d = date.parse(dt[i]);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(d != null ) {
                cal.setTime(d);
                re[i] = cal.get(Calendar.DAY_OF_YEAR);
            }
        }
    }//fill in array of DOY's
    return re;
}

You need to surround your parse method with try-catch clause. It seems one of the entries is not in correct format. And when you catch that exception you can check what exactly was the cause.

Upvotes: 1

Related Questions