Friday, March 12, 2010

Java Time Difference Function

In one of project, there was need to find difference between two timestamps. It is normally required when you have from and to time fields.

In our case we wanted difference between to time and from time like "12.21pm" and "11.21am". So I have written the following function. With specifying string format user will be able to get difference in seconds.

Click link for pattern format letters

Function:

public static long fnGetTimeDifference(String strFormat, String strFromTime, String strToTime)
{
long lDifference = -1;

try
{
SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat(strFormat);

Date oFromTimeDate = oSimpleDateFormat.parse(strFromTime);
Date oToTimeDate = oSimpleDateFormat.parse(strToTime);

lDifference = (oToTimeDate.getTime() - oFromTimeDate.getTime()) / 1000;

System.out.println("Time Difference: " + lDifference + " seconds");
}
catch (ParseException e1)
{
e1.printStackTrace();
}

return lDifference;
}


Function call example:

fnGetTimeDifference(“hh:mma”, “11.21am”, “12.21pm”);