Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
We use java.util.SimpleDateFormat to have today's date shown and another date entered as indicated by our pattern ( uppercase MM ! ).
new Date() gives us today's date, plus the time, but we won't use the latter.
Show it in the first textfield.
Hitting 'Enter' in the 2nd field or a button click takes us to actionPerformed,...
where we instruct SimpleDateFormat to be strict in validating the date to be entered.
The textfield's text is parsed according to the pattern we gave SimpleDateFormat.
If approved ( no exception ), the method doit is called.
Here we use java.util.GregorianCalendar.
The current moment in time.
Its time fields, ALL OF THEM, are cleared for the comparisons and calculation that are about to take place.
Another instance for the date entered.
If a future date is entered,...
we make another instance, a genuine copy of the 'today' instance, since we want to keep the latter unchanged and perform a calculation on the copy.
(GregorianCalendar) is there to cast the Object reference returned by the clone method to the type required.
Keep incrementing its day of the month field and our days counter,...
as long as the date calculated is before the date entered.
The calculation cycles through months ( and years ) as needed.
This same technique can be used to add months, hours or what have you, by replacing Calendar.DATE with the proper constant. To go BACK in time, you pass a NEGATIVE value as 2nd argument.
Regarding the hour fields, for example :
14 would be
CLEARING just ONE of them WILL NOT AFFECT THE OTHER(s), so you might suddenly be looking at 12 noon instead of midnight or experience similar joy.
For calculating precise differences between moments in time you can use Calendar's method getTimeInMillis or Date's getTime method, which return the moment as a number of milliseconds since Jan 1st,1970 00:00 ( as does System.currentTimeMillis, that can also come in handy ).
dtcalc = today wouldn't do the job, because then dtcalc would point to one and the same instance as 'today' and dtcalc.add would change the contents of that same instance.
March ( ! ) 18th 16:15:00 2006
January = 0 , March = 2 , mmmmkay ?
If you lookup GregorianCalendar in the documentation, don't forget to have a look at the methods inherited from Calendar. ( links at the bottom of the page )
Lookup Date, too, and notice that most methods must not be used anymore, they've been DEPRECATED. But Date still has its uses as this lesson shows and it's lightweight compared to the Calendar classes.