如何计算两个日期之间的差异,并以小时:分钟:秒?
的格式显示示例:
StartTime:2016-12-20T04:30 结束时间:2016-12-22T05:00
输出应为48小时30分0秒。
这是我尝试过的:
Long diff = (endDate.get time() -startDate.gettime())/1000;
Log.d("App","difference in hour is"+diff/1000/60/60);
Mins = diff/1000/60;
Seconds = diff/1000;
使用此代码我将小时数作为正确值。但分钟和秒值没有得到正确的值。
答案 0 :(得分:8)
尝试此功能: -
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
//long elapsedDays = different / daysInMilli;
//different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d hours, %d minutes, %d seconds%n",
elapsedHours, elapsedMinutes, elapsedSeconds);
}
答案 1 :(得分:2)
尝试
1。首先添加以下方法,然后使用parseDate。
Date startDate = parseDate("2016-12-20T04:30");
Date endDate = parseDate("2016-12-22T05:00");
2。计算这两个差异b / w
long differenceInMillis = endDate.getTime() - startDate.getTime();
3. 使用formatElapsedTime方法格式化差异
String formattedText = formatElapsedTime(differenceInMillis/1000); //divide by 1000 to get seconds from milliseconds
//Result will be 48hours 30minutes 0 seconds
public static Date parseDate (String strDate) {
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm");
Date date1 = null;
try {
date1 = dateFormat.parse (strDate);
}
catch (ParseException e) {
e.printStackTrace ();
}
return date1;
}
public static String formatElapsedTime (long seconds) {
long hours = TimeUnit.SECONDS.toHours(seconds);
seconds -= TimeUnit.HOURS.toSeconds (hours);
long minutes = TimeUnit.SECONDS.toMinutes (seconds);
seconds -= TimeUnit.MINUTES.toSeconds (minutes);
return String.format ("%dhr:%dmin:%dsec", hours, minutes, seconds);
}
答案 2 :(得分:1)
import java.util.Calendar;
public class DateDifferenceExample {
public static void main(String[] args) {
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Set the date for both of the calendar instance
cal1.set(2006, Calendar.DECEMBER, 30);
cal2.set(2007, Calendar.MAY, 3);
// Get the represented date in milliseconds
long millis1 = cal1.getTimeInMillis();
long millis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = millis2 - millis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");
}
}
答案 3 :(得分:0)
使用更新的 API 对旧问题的新答案:java.time
您可以编写一个实际接受日期时间作为 String
以及时区的方法,然后通过为此目的设计的类来计算差异:java.time.Duration
这是一个代码示例:
public static String getDifference(String firstDt, String secondDt, String zone) {
// create the zone for the calculation just to respect daylight saving time
ZoneId zoneId = ZoneId.of(zone);
// then parse the datetimes passed and add the time zone
ZonedDateTime firstZdt = ZonedDateTime.of(
LocalDateTime.parse(firstDt), zoneId
);
ZonedDateTime secondZdt = ZonedDateTime.of(
LocalDateTime.parse(secondDt), zoneId
);
// calculate the duration between the two datetimes
Duration duration;
/*
* the JavaDocs of Duration tell us the following:
*
* "The result of this method can be a negative period
* if the end is before the start.".
*
* So we need to make sure the older datetime will be
* the "start" in the method "between(start, end)"
*/
if (firstZdt.isAfter(secondZdt)) {
duration = Duration.between(secondZdt, firstZdt);
} else {
duration = Duration.between(firstZdt, secondZdt);
}
// store the amount of full hours the duration has
long hoursBetween;
hoursBetween = duration.toHours();
// calculate the minutes left from the full duration in minutes
long minutesBetween;
minutesBetween = duration.toMinutes() - (hoursBetween * 60);
// calculate the seconds left from the full duration in seconds
long secondsBetween;
secondsBetween = duration.getSeconds() - (duration.toMinutes() * 60);
// build the result String, take care of possibly missing leading zeros
StringBuilder resultBuilder = new StringBuilder();
resultBuilder.append(hoursBetween).append(" hours ");
if (minutesBetween < 10 && minutesBetween > 0)
resultBuilder.append("0");
resultBuilder.append(minutesBetween).append(" minutes ");
if (secondsBetween < 10 && secondsBetween > 0)
resultBuilder.append("0");
resultBuilder.append(secondsBetween).append(" seconds");
return resultBuilder.toString();
}
如果您在 main
...
public static void main(String[] args) {
String timeDiff = getDifference("2016-12-20T04:30", "2016-12-22T05:00", "UTC");
System.out.println(timeDiff);
}
...你会得到以下输出:
48 hours 30 minutes 0 seconds
上面的代码是在 Java 8 中使用的代码,后来,Duration
得到了 toHoursPart()
、toMinutesPart()
和 toSecondsPart()
方法,它们实际上进行了必要的计算内部。
会改变的代码(在 Java 11 中尝试过):
// store the amount of full hours the duration has
long hoursBetween;
hoursBetween = duration.toHoursPart();
// calculate the minutes left from the full duration in minutes
long minutesBetween;
minutesBetween = duration.toMinutesPart();
// calculate the seconds left from the full duration in seconds
long secondsBetween;
secondsBetween = duration.toSecondsPart();