joschplusa
joschplusa

Reputation: 1403

SimpleDateFormat returns invalid date

I'm facing a really strange problem I haven't seen before. I have a date in milliseconds and want to display it as a readable date. This is my code:

if (validUntil == 0) {
  return activity.getResources().getString(R.string.forever);
} else {
  Date startDate = new Date(validFrom);
  Date endDate = new Date(validUntil);
  if (startDate.compareTo(endDate) < 0) {
    String date = sdf.format(startDate) + " - " + sdf.format(endDate);
    return date;
  } else if (startDate.compareTo(endDate) == 0) {
    return activity.getResources().getString(R.string.forever);
  }
}

As you can see I just want to create a string which shows the time span. When I debug into my code, the date objects contain the right values while sdf.format(...) gives me an invalid date.

Example:

I get a simillar result for the end date.

What am I doing wrong?

Upvotes: 3

Views: 1124

Answers (3)

Semyon Danilov
Semyon Danilov

Reputation: 1773

You get minutes instead of months. Your pattern should be like this: "dd.MM.yyyy"

Upvotes: 5

DSR
DSR

Reputation: 185

Looks like your date format string is incorrect. This works:

public static void dateFormat(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(format.format(new Date()));
    }

Result:

2013-07-29

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49432

Probably it seems you have used mm to denote months , but it should be MM . Look at the documentation.

M month in year

m minute in hour

Try:

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

Upvotes: 9

Related Questions