Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct Date - An efficient way

Tags:

java

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.

like image 922
Cheok Yan Cheng Avatar asked Mar 04 '10 14:03

Cheok Yan Cheng


2 Answers

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.

like image 68
helios Avatar answered Nov 04 '22 10:11

helios


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

like image 23
Jon Skeet Avatar answered Nov 04 '22 10:11

Jon Skeet