Construct Date - An efficient way

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


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.

Tags:

Java