Tuesday, June 11, 2013

Time difference using Joda Time Utility jar

/*
 * Thanooj - using Joda Time Utility jar 
 */
package com;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;

public class JodaDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {

  String dateStart = "01/11/2012 08:28:36";
  String dateStop = "01/12/2012 10:31:40";

  SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

  Date d1 = null;
  Date d2 = null;

  try {
   d1 = format.parse(dateStart);
   d2 = format.parse(dateStop);

   DateTime dt1 = new DateTime(d1);
   DateTime dt2 = new DateTime(d2);
   System.out.println("Time it took to execute this method ::\n");
   System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");
   System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
   System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes and ");
   System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}


output:
-------
Time it took to execute this method ::

1 days, 2 hours, 3 minutes and 4 seconds.

No comments: