MiloŇ° MiloŇ° - 5 months ago 11
Java Question

Android SimpleDateFormat, how to use it?

I am trying to use the Android

SimpleDateFormat
like this:

String _Date = "2010-09-29 08:45:22"
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");

try {
Date date = fmt.parse(_Date);
return fmt.format(date);
}
catch(ParseException pe) {
return "Date";
}


The result is good and I have: 2010-09-29

But if I change the
SimpleDateFormat
to

SimpleDateFormat("dd-MM-yyyy");


the problem is that I will got 03-03-0035 !!!!

Why and how to get the format like
dd-MM-yyyy
?

Answer

I assume you would like to reverse the date format?

SimpleDateFormat can be used for parsing and formatting. You just need two formats, one that parses the string and the other that returns the desired print out:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(dateString);

SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
Comments