Monday, October 29, 2007

Java : Creating a date

The old format was

Date date = new Date ("2007/10/29") but that has long been deprecated.

Use this:



DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd");
try
{
Date date = dfm.parse("1990-01-01");
}

catch (Exception e)
{
System.out.println("Date exception is: " + e.getMessage());
e.printStackTrace();
}



If you wanted to add the time:



DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try
{
Date date = dfm.parse("1990-01-01 12:40:00");
}

catch (Exception e)
{
System.out.println("Date exception is: " + e.getMessage());
e.printStackTrace();
}



Enjoy!

No comments: