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.
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.
"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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With