Bear
Bear

Reputation: 5152

String to Calendar object

Here is my target format:

19 AUG 2011

And I try to convert this string to Calendar object by following code, but variable "date" remains null..

SimpleDateFormat formatter ; 
        Date date = null ; 
        formatter = new SimpleDateFormat("dd MMM yyyy");
        try {
         date = formatter.parse(returnDate);
    } catch (ParseException e) {            
        e.printStackTrace();
    } 
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);

Does anyone know what's going wrong? Thank You.

FYI, exception msg:

Unparseable date: "19 Aug 2011" at java.text.DateFormat.parse(Unknown Source)

But I don't think it is useful...

Upvotes: 0

Views: 3309

Answers (3)

Dubas
Dubas

Reputation: 2876

The SimpleDateFormat depends on the current calendar and the calendar on the locale by default. Depending the locale and the calendar probably "AUG" is not a valid text for the month.

AUG is a valid string for US Locale but for example not for ES Locale.

You can force the locale to US adding it to the SimpleDateFormat:

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy",Locale.US);

With the US locale you can parse correctly the string if the date has US 2 letter months.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

Something is going wrong with the parsing. You aren't finding out about it because of this:

 catch (ParseException e) {            

 } 

That's basically saying, "I don't care what goes wrong - ignore it." At the very least you should be logging the error, and more likely letting the exception bubble up.

Exceptions are an incredibly important diagnostic tool - don't just catch them and ignore them.

EDIT: Now that the question's changed, we can see the exception - but the code is still continuing as if nothing's happened. Even if you do want to mostly ignore the exception, you need to decide what value you want date to have if parsing failed. Clearly null is unhelpful - so you need to either let the exception bubble up (to let the caller know that parsing failed) or return some difference value (e.g. a default date, or today, or something like that).

Now, as it happens, letting the exception bubble up makes the code simpler too. It doesn't throw an exception on my machine, but maybe it will on yours:

import java.util.*;
import java.text.*;

public class Test {

    public static void main(String[] args) throws Exception {
      Calendar cal = parseReturnDate("19 AUG 2011");
      System.out.println(cal);
    }

    public static Calendar parseReturnDate(String returnDate) 
        throws ParseException {
      SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
      Date date = formatter.parse(returnDate);
      Calendar cal=Calendar.getInstance();
      cal.setTime(date);
      return cal;
    }       
}

Note how we don't need to declare variables separately to assigning them values, and that now we're letting the exception bubble up we can just assign date its useful value directly.

My guess is that your default time zone doesn't use "AUG" as a short month name - but I can't really tell without seeing the exception. If that's the case, you might want to specify the locale when constructing the formatter:

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy",
                                                  Locale.US);

You might also want to specify a time zone.

(As an aside, Joda Time is a far superior API for date and time handling. If you're doing any significant work with the value afterwards, I'd definitely recommend using it over Date/Calendar.)

Upvotes: 7

Nico Huysamen
Nico Huysamen

Reputation: 10417

I just tried your code and it works fine. Try running the following:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Playground {
    
    public static void main(String... args) {
    
        String returnDate = "19 AUG 2011";
        SimpleDateFormat formatter ; 
        Date date = null ; 
        formatter = new SimpleDateFormat("dd MMM yyyy");
    
        try {
            date = formatter.parse(returnDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
        System.out.println(date.toString());
    
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
    
        System.out.println(cal.getTime().toString());
    }
}

OUTPUT:

Fri Aug 19 00:00:00 CAT 2011

Fri Aug 19 00:00:00 CAT 2011

Upvotes: 0

Related Questions