import java.util.*; import java.text.*; public class Test1 { private static String getDateDifference(String format, Date d1, Date d2 ){ long dl1 = d1.getTime(); long dl2 = d2.getTime(); long sec2Millisec = 1000; long minute2Millisec = sec2Millisec*60; long hour2Millisec = minute2Millisec*60; long day2Millisec = hour2Millisec*24; long diff = (dl2-dl1); long days = (diff)/(day2Millisec); diff = diff%day2Millisec; long hours = (diff)/(hour2Millisec); diff = diff%hour2Millisec; long mins = (diff)/(minute2Millisec); diff = diff%minute2Millisec; long secs = diff/sec2Millisec ; return String.format( format, days, hours, mins, secs); } public static void main(String[] args){ try { Date d1 = new Date(); Date d2 = new Date(d1.getTime() + 1113660*1000); System.out.println (Test1.getDateDifference(" %d days, %d hours, %d mins, %d secs", d1, d2)); }catch (Exception e){ System.out.println("err = " + e); e.printStackTrace(); } } } |
Tuesday, November 23, 2010
Date in java difference anyone ?
Turns out it not simple function call to get the difference between two dates and display the result is a nicely formatted output. I ended up doing this (With liberal help from google )
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment