tags:

views:

345

answers:

4

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 in advance

+7  A: 

Use SimpleDateFormat.

[Edited]

Few sample codes.

Adeel Ansari
Just have to be careful of the threading problems with that! I've had the weirdest bugs arise from use of SimpleDateFormat
chillysapien
+3  A: 

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"
Jon Skeet
+6  A: 

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 awful.

Ludwig Wensauer
+2  A: 
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 OK, no matter if you write as argument "2008-1-1" or "2008-01-01".

Fernando Miguélez