Adeel's solution is great if you need to use the built-in Java processing of date and time, but personally I would rather use Joda Time . When it comes to formats, the main advantage of Joda Time is that the formatter is stateless, so you can safely share it between streams. Code example:
DateTimeFormatter parser = DateTimeFormat.forPattern("YYYY-MD"); DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-DD"); DateTime dt = parser.parseDateTime("2008-1-1"); String formatted = formatter.print(dt); // "2008-01-01"
source share