Keywords: Android | SimpleDateFormat | Date Formatting
Abstract: This article provides a comprehensive guide to using SimpleDateFormat in Android, addressing common pitfalls like parsing errors when formats mismatch. Step-by-step examples illustrate how to use separate SimpleDateFormat instances for parsing and formatting, with an introduction to Java 8's DateTimeFormatter for modern solutions, supplemented by date format symbol references to help developers avoid typical mistakes.
Introduction
In Android development, date handling is a frequent task, and SimpleDateFormat is a widely used class for parsing and formatting dates. However, incorrect usage can lead to unexpected outcomes, such as when changing the format from "yyyy-MM-dd" to "dd-MM-yyyy" results in erroneous output like "03-03-0035".
Understanding the Problem
When parsing a date string, SimpleDateFormat expects the input to match the specified pattern. Mismatched patterns can cause misinterpretation of date components, leading to errors. The key issue is that parsing and formatting should utilize separate instances.
Correct Solution
Use two SimpleDateFormat instances: one for parsing the original string and another for formatting the output. Example code:
String dateString = "2010-09-29 08:45:22";
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(dateString);
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
Modern Approach with Java 8
Java 8 and later offer DateTimeFormatter for more robust date handling. Example:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
TemporalAccessor date = fmt.parse(dateString);
Instant time = Instant.from(date);
DateTimeFormatter fmtOut = DateTimeFormatter.ofPattern("dd-MM-yyyy").withZone(ZoneOffset.UTC);
return fmtOut.format(time);
Date Format Symbols Reference
Common date format symbols include: d for day of month, M for month, y for year, etc. For a full reference, consult official documentation.
Conclusion
By employing separate instances for parsing and formatting, and considering modern APIs like DateTimeFormatter, developers can effectively avoid common errors in Android date handling.