m0skit0 Here it is in .Net. Eight lines of code. Show it in Java. If you think you can then prove it.
Dim StartDate As Date = Now
Dim EndDate As Date = Now
EndDate = EndDate.AddSeconds(15)
Dim Months As Long = DateDiff(DateInterval.Month, StartDate, EndDate)
Dim Days As Long = DateDiff(DateInterval.Day, StartDate, EndDate)
Dim Hours As Long = DateDiff(DateInterval.Hour, StartDate, EndDate)
Dim Minutes As Long = DateDiff(DateInterval.Minute, StartDate, EndDate)
Dim Seconds As Long = DateDiff(DateInterval.Second, StartDate, EndDate)
The code below is wrong. The second half starting with Calendar cal2 = would be in a TimerTask to calculate the difference between two times and break it down to months, days, hours, minutes, and seconds.
Towards the top I get the current date/time and then add 15 seconds to it. Then attempt to calculate the difference. It seems to work depending on how much time I add to the second Date. I've been struggling with this for days. At one point everything matched up except the hours were 4 hours off, but I am GMT+8, so that made no sense. That is what I added in the TimeZone(UTC). I read about Joda time, but I'm still new to Java and Android and after several attempts to install the libraries and went back to pure Java. Painful.
Who ever devised date/times is Java either insane or a masochist or both.
(In .Net this was 8 lines of code. Eight!)
Calendar cal = Calendar.getInstance();
TimeZone UTC = TimeZone.getTimeZone("UTC");
cal.setTimeZone(UTC);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
endDate = dateFormat.parse(String.valueOf(year) + "-" + String.valueOf(month)
+ "-" + String.valueOf(day) + " " + String.valueOf(hour)
+ ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds +15));
dateFormat.setTimeZone(UTC);
} catch (ParseException ex) {
Log.d("ParseException", ex.toString());
}
Calendar cal2 = Calendar.getInstance();
TimeZone UTC2 = TimeZone.getTimeZone("UTC");
cal.setTimeZone(UTC2);
Date beginDate = cal.getTime();
long millis = endDate.getTime() - beginDate.getTime();
if (TimeZone.getDefault().inDaylightTime( new Date())) {
millis += 3600000;
}
String Months = (new SimpleDateFormat("M")).format(new Date(millis));
String Days = (new SimpleDateFormat("d")).format(new Date(millis));
String Hours = (new SimpleDateFormat("h")).format(new Date(millis));
String Minutes = (new SimpleDateFormat("m")).format(new Date(millis));
String Seconds = (new SimpleDateFormat("s")).format(new Date(millis));