Friday, May 4, 2012

Time for dates?

In Java, there often comes a scenario where we need to compute difference between two timestamps. Time difference, date, can it get any easier than that? Well, it is not that straight forward as it sounds as with real life. Added to that Java has a dozen different classes - Date, Time, Calendar, DateTime, Timestamp. Here is one easy way of computing time difference between 2 timestamps represented by the Date object - 



public static String getTimeDifference(Date date1, Date date2)
   {
      long difference = date1.getTime() - date2.getTime();
      AppUtil.print("Date1:" + date1);
      AppUtil.print("Date2:" + date2);
      String timeDifference = "";
      difference = Math.abs(difference);
      AppUtil.print("Diff:" + difference);
      if(difference==0) {
         timeDifference = "-";
      } else {
        long hours = difference/(1000 * 60 * 60);
        long minutes = (difference / (1000 * 60)) % 60;
        long seconds = (difference / 1000) % 60 ;
        if(hours>0) {
           timeDifference+= (hours + " hours ");
           AppUtil.print("hrs:" + hours);
        }
        if(minutes>0) {
           timeDifference+= (minutes + " min ");
        }
        if(seconds>0) {
           timeDifference+= (seconds + " sec ");
        }
      }
      AppUtil.print("time:" + timeDifference);
      return timeDifference;
   }


Also, as it is often with dates, they get pretty fussy. Sometimes, we need to format them the way we want them. Especially when you are passing Date or Timestamp objects from database obtained via JDBC. So here goes an example to format dates/times - 


Date timeReference = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS").parse(endTime);



No comments:

Post a Comment