8

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
  • 21,778
  • 41
  • 170
  • 332

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
  • 40,517
  • 9
  • 64
  • 103
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,556
  • 3
  • 23
  • 36
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,780
  • 10
  • 51
  • 94
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,851
  • 2
  • 18
  • 32