9

The constructor java.util.Date(int,int,int) is deprecated. Is there a way to set a date easy as that in Java? What's the non-deprecated way to do this?

Date date = new Date(2015, 3, 2);
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378

4 Answers4

16

What's the non-deprecated way to do this?

Java 8 to the rescue:

LocalDate localDate = LocalDate.of(2015, 3, 2);

And then if you really really need a java.util.Date, you can use the suggestions in this question.

For more info, check out the API or the tutorials for Java 8.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
7

By using

java.util.Calendar

is one possibility:

   Calendar calendar = Calendar.getInstance();
   calendar.set(Calendar.YEAR, 2015);
   calendar.set(Calendar.MONTH, 4);
   calendar.set(Calendar.DATE, 28);
   Date date = calendar.getTime();

Keep in mind that months are 0 based, so January is 0-th month and december 11th.

zubergu
  • 3,646
  • 3
  • 25
  • 38
3

Try Calendar.

Calendar calendar = Calendar.getInstance();
Date date =  calendar.getTime();

I am sure there also is a method which takes the values you provide in your example.

Marged
  • 10,577
  • 10
  • 57
  • 99
0

Use the Calendar class, specifically the set(int year, int month, int date) for your purpose. This is from Java 7, but you'll have equivalent - setDate(), setYear() etc. - methods in older versions.

legendofawesomeness
  • 2,901
  • 2
  • 19
  • 32