Alex Rivera | Logout

Set Date in a single line

Asked 2010-05-20T20:26:31.500
54

According to the Java API, the constructor Date(year, month, day) is deprecated. I know that I can replace it with the following code:

Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, theYear);
myCal.set(Calendar.MONTH, theMonth);
myCal.set(Calendar.DAY_OF_MONTH, theDay);
Date theDate = myCal.getTime();

However, I would like something shorter to replace it with (ideally one to two lines).

Edit
Report

2 Answers

82

You could use new GregorianCalendar(theYear, theMonth, theDay).getTime():

public GregorianCalendar(int year, int month, int dayOfMonth)

Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

answered 2010-05-20T20:30:02.367
10

Calendar has a set() method that can set the year, month, and day-of-month in one call:

myCal.set( theYear, theMonth, theDay );
answered 2010-05-20T20:34:46.807

Your Answer