irobotxx
irobotxx

Reputation: 6063

parsing only the Year in a DateFormat Java

I get a returned parsed JSON result with string values in the form of dates like "27-11-2012" which i parse to a date Object. my code for this is:

public Date stringToDateReport(String s){
        //Log.d(TAG,    "StringToDateReport here is " + s);
        DateFormat format;
        Date date = null;

        //if(s.matches(""))
         format = new SimpleDateFormat("dd-MMM-yyyy");

        try {

            date = (Date)format.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

now my issue is, a feature has been implemented that sometimes the json only returns a year object like "2012" and is giving me an "ParseException: Unparseable date" as expected. I was thinking of using regex to match the string pattern and parse from there, but not sure how to do that. Any ideas and also anyway to parse only year in a DateFormat?

Upvotes: 0

Views: 3912

Answers (3)

Houcine
Houcine

Reputation: 24181

public Date stringToDateReport(String strDate){
    DateFormat formatnew SimpleDateFormat("dd-MM-yyyy");
    Date date = null;

    if(strDate.length()==4) {
        format = new SimpleDateFormat("yyyy");
    }
    try {
        date = (Date)format.parse(strDate);
    } catch (ParseException e) {
        //error parsing date
        e.printStackTrace();
    }
    return date;
}

then call it like this :

String strDate = yourJson.getString("date");
Date d = stringToDateReport(strDate);

Upvotes: 0

Renato Lochetti
Renato Lochetti

Reputation: 4568

Try this code

public Date stringToDateReport(String s){
    //Log.d(TAG,    "StringToDateReport here is " + s);
    DateFormat format;
    Date date = null;

    if(s.indexOf("-") < 0){
     format = new SimpleDateFormat("yyyy");
    }else{
     format = new SimpleDateFormat("dd-MMM-yyyy");
    }
    try {

        date = (Date)format.parse(s);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

Is there the possibility in have another format in the String s ? Or just these two?

Upvotes: 2

ppeterka
ppeterka

Reputation: 20726

I'd try:

public Date stringToDateReport(String s){
    DateFormat format;
    Date date = null;

    format = new SimpleDateFormat("dd-MM-yyyy");

    if(s.length()==4) {
        format = new SimpleDateFormat("yyyy");
    }
    try {
        date = (Date)format.parse(s);
    } catch (ParseException e) {
        //you should do a real logging here
        e.printStackTrace();
    }
    return date;
}

The logic behind is to check if the string is only 4 long, then apply the different format. In this case, this easy method is sufficient, but in other methods, the use of regexes might be required.

Upvotes: 2

Related Questions