import java.text.SimpleDateFormat;
import java.util.Date;
public class Time_Difference{
public static void main(String[] args) {
String dateStart = "01/15/2012 09:29:58";
String dateStop = "01/15/2012 10:29:58";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null; //Doubt here...
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
I have 3 questions in the above code block
1) why do we assign null to the Date variables d1 & d2?
2)What exactly does does d1 and d2 return after the executing the following lines of code?
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
I know we are converting date string to some integer value ...But what exactly is that value??
3] please explain the below logic of how the diff between d1 & d2 is converted into seconds,minutes, hours etc..
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
Thank you i really appreciate ur time and support....It means a lot for a beginner like me