Neilers
Neilers

Reputation: 421

SimpleDateFormat parse and format on same date string gives different results

I've got a simple task, that is, to convert a date that's in this format: "2014-06-13" to this format: "January 6, 2013"

I've declared two SimpleDateFormat objects for this:

private SimpleDateFormat mInputFormat = new SimpleDateFormat("yyyy-MM-DD", Locale.ENGLISH);
private SimpleDateFormat mOutputFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);

So I write the code to do so:

Log.v(TAG, "orig: " + releaseDate);
try {
    Date date = mInputFormat.parse(releaseDate); // create a date object using the first pattern
    Log.v(TAG, "parsed:" + mInputFormat.format(date));
    String newDate = mOutputFormat.format(date); // format the date object into the new format
    Log.v(TAG, newDate);
    aq.id(R.id.text_2).text(newDate); // sets the date
} catch (ParseException e) {
    e.printStackTrace();
}

The thing is, the dates are completely off. Here's what's printed on the logs:

09-15 20:07:49.035: V/TwoLinerListItemView(26700): orig: 2014-06-13
09-15 20:07:49.035: V/TwoLinerListItemView(26700): parsed:2014-01-13
09-15 20:07:49.035: V/TwoLinerListItemView(26700): January 13, 2014

I am so baffled as to why these results are so different. First of all, the original string, 2014-06-13 was parsed into a date object using the input format. Then, I formatted that resulting string using the exact same inputdate format, and then and there the date was changed. It's like you parsed the string "1" then it became the integer 2, then when you made the integer back to a string it became 3. Whut.

Upvotes: 0

Views: 1069

Answers (1)

Opiatefuchs
Opiatefuchs

Reputation: 9870

You used the big D in the first Format:

     new SimpleDateFormat("yyyy-MM-DD", Locale.ENGLISH);

but D is for Day in Year. You have to use dd, that´s for day in month. Change it to:

     new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

Upvotes: 1

Related Questions