Java date formatting?

后端 未结 4 535
深忆病人
深忆病人 2021-01-19 16:40

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

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

Can anybody help me? Thanks

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 17:27

    Adeel's solution is fine if you need to use the built-in Java date/time handling, but personally I'd much rather use Joda Time. When it comes to formats, the principle benefit of Joda Time is that the formatter is stateless, so you can share it between threads safely. Sample code:

    DateTimeFormatter parser = DateTimeFormat.forPattern("YYYY-M-D");
    DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-DD");
    
    DateTime dt = parser.parseDateTime("2008-1-1");
    String formatted = formatter.print(dt); // "2008-01-01"
    

提交回复
热议问题