Java date formatting?

I want to read the date in YYYY-MM-DD format.

But if I specify a date, for example, 2008-1-1, I want to read it as 2008-01-01.

Can someone help me? thanks in advance

+4
source share
4 answers

Or use the much better Joda Time lib.

DateTime dt = new DateTime(); System.out.println(dt.toString("yyyy-MM-dd")); // The ISO standard format for date is 'yyyy-MM-dd' DateTimeFormatter formatter = ISODateTimeFormat.date(); System.out.println(dt.toString(formatter)); System.out.println(formatter.print(dt)); 

The date and calendar API is terrible.

+11
source

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" 
+7
source
 import java.text.*; public class Test { public static void main(String args[]) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD"); System.out.println(sdf.parse(args[0]).toString()); } catch(Exception e) { e.printStackTrace(); } } } 

This works fine, regardless of whether you write as the argument "2008-1-1" or "2008-01-01".

+3
source

All Articles