Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42690

Construct Date - An efficient way

May I know what is the most efficient way to construct a date object using a specific day, month, and year.

Date(int year, int month, int day) 

This construct is depreciated. Hence, what I usually do is:

Calendar calendar = Calendar.getInstance();
Date date = calendar.set(year, month, date).getTime();

However, my understanding is that Calendar.getInstance() is rather expensive. What is the most efficient way to construct a Date object? Or should I just use Date(int year, int month, int day) quietly without telling the rest?

Please don't suggest using any third-party library.

Upvotes: 17

Views: 13749

Answers (4)

duffymo
duffymo

Reputation: 308763

I would simply do this:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date thisDate = formatter.parse("2010-03-04");

It's pretty efficient from a lines of code standpoint; I can't speak to its runtime efficiency vis a vis Calendar.

Ten years later in 2020: the only right answer is to use classes in java.util.time package.

LocalDate localDate = LocalDate.now();
LocalDate.of(2020, 3, 7);
LocalDate.parse("2020-03-07");

Upvotes: 2

helios
helios

Reputation: 13841

With this you can avoid the innecesary "now time" instance creation.

Date coolDate = new GregorianCalendar(year, month, day).getTime();

You can check GregorianCalendar javadoc for other constructors. You have date+time, and timezone.

Anyway I agree with Jon Skeet that it's not so expensive. I agree with you that code doesn't need a default "now" initialization.

Upvotes: 20

Michael Borgwardt
Michael Borgwardt

Reputation: 346270

Whatever you use, as long as it's in the Java Standard API, it will involve the use of Calendar (both the Date constructor and SimpleDateFormat use it internally), so there's no point fretting about that class's supposed inefficiency.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500425

"Rather expensive" is somewhat vague. Have you actually tried using the code you've supplied, measured it and found it to be too expensive? Do you have a concrete idea of how cheap you need this operation to be?

Also, you haven't specified which time zone you want the value in the Date to represent. UTC? The default time zone? What time of day do you want it to be - midnight, or the current time of day? Your current code will keep the existing time of day - is that really what you want?

(As I mentioned in a comment, I would strongly suggest you move to Joda Time - but even if you don't, you should still check whether or not you've actually got a problem with your existing code before looking for a solution.)

Upvotes: 8

Related Questions