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);
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);
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.
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.
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.
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.