10

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

4 Answers 4

17

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

4 Comments

This class is singleton. What if I want to change the date and store different dates e.g. inside a database?
Oh, or is it singleton? ^^
I don't get your point ...
It would be a problem if it was singleton but the docu says it isn't so your suggestion is good.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.