Reputation: 11
I want to modify the date in Java. That's no problem, but I'm a bit confused about how I should do this.
1.
Calendar c = Calendar.getInstance();
c.set(2010,9,10,6,0);
2.
Calendar c = Calendar.getInstance();
c.set(c.YEAR, 2010);
c.set(c.MONTH, 9);
c.set(c.DATE, 10);
c.set(c.HOUR, 6);
c.set(c.MINUTE, 0);
Which one is the better way? If I use the second way I have to type a bit more and I learned that the code should be as short as possible. On the other side the second way is a bit more clear.
Upvotes: 1
Views: 67
Reputation: 86774
The ONLY way to modify a date is in one atomic operation. Doing it a field at a time will result in surprisingly incorrect results sometimes. When you create a new Calendar
it gets initialized with todays date. Suppose today is May 31st and you set the month to June, intending to set the day next. When you set the month, to June, 31 is no longer valid, so the date gets "normalized" to July 1st. You then set the day, but now the month is wrong.
You can construct quite a few of these "interesting" cases. Some will fail if you set the month first, and some will fail if you set the day first, so there's no order that is guaranteed to work for all cases. Set the date as a single operation.
Here are some examples:
Today Changes Result
5/31/2013 MM->6, DD->12 7/12/2013 (not 6/12)
6/01/2013 DD->31, MM->07 7/01/2013 (not 7/31)
Upvotes: 1
Reputation: 93
Well Stefan, I think you should go for the cleaner approach. The first method has only two lines of code to solve your problem . You should adopt it. From my development experience, I have learned that the LOC (Line Of Code) really matters in the maintenance of code and we should always think about solving a problem with minimum lines of code. So I think you should take advantage of multi-parameters setter API.
Thanks!
Upvotes: 0
Reputation: 91
A short code is not all time the good way in Java (or other language). You have to be clear for you and for other developers who want to use your code.
So, in my opinion, you can use the first method but with more java doc and comments than the second method which is the most explicit (attention : the second method is the most explicit but it need comments too...).
Upvotes: 0
Reputation: 441
Try this, but ctrl+space could help you next time.
Calendar cal = Calendar.getInstance();
cal.set(year, month, date, hourOfDay, minute);
Thanks
Upvotes: 2