Sep 13

The Calendar class can be used to do a variety of date arithmetic


Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, numberOfDays);
date = cal.getTime(); 

written by objects \\ tags: ,

Sep 13

Problem is you have two Date instances and you want to get the elapsed time between them.

Getting the number of seconds is easy, you can just take the difference of value returned by the getTime() method.

   long elapsed = end.getTime() - start.getTime();

But what if you want to know how many days, hours and minutes have elapsed.

One method is to do the calculations yourself

   final long ONE_SECOND = 1000;
   final long ONE_MINUTE = ONE_SECOND * 60;
   final long ONE_HOUR = ONE_MINUTE * 60;
   final long ONE_DAY = ONE_HOUR * 24;
   long days = elapsed / ONE_DAY;
   elapsed %= ONE_DAY;
   long hours = elapsed / ONE_HOUR;
   elapsed %= ONE_HOUR;
   long minutes = elapsed / ONE_MINUTE;
   elapsed %= ONE_MINUTE;
   long seconds = elapsed / ONE_SECOND;

Or alternatively if you are just interested in the numbers of hours, minutes and seconds where the elapsed period is less than 24 hours then you can use the date/time handling classes provided by Java

DateFormat dateFormat = 
   new SimpleDateFormat("HH 'hours' mm 'minutes' ss 'seconds'");
Calendar cal = Calendar.getInstance();
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTime(new Date(elapsed));
System.out.println(dateFormat.format(cal.getTime()));

NB. The second method can actually be adapted to get the number of days as well if required.

written by objects \\ tags: , , , ,

Aug 03

All the constructors and methods of the Date class that allow you to set the date value are deprecated so how do we set a Date instance to the date we need it to be.

Answer is to use the Calendar class and use the various set() methods to set the date required. Once you have that set you can use the getTime() method to get your required Date.

Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
Date date = cal.getTime();

An alternative is to use the GregorianCalendar class directly

Calendar cal = new GregorianCalendar(year, month, day);
Date date = cal.getTime();

written by objects \\ tags: , ,