6

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
  • 18,764
  • 34
  • 144
  • 286

4 Answers4

14

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
  • 39,413
  • 8
  • 61
  • 94
5

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,341
  • 3
  • 22
  • 34
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
  • 9,123
  • 9
  • 45
  • 87
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,783
  • 1
  • 17
  • 32