就像我有5次
1. 05:12:02
2. 19:12:52
3. 40:12:14
4. 56:54:10
5. 41:12:12
-----------
Total Seconds : 0#####..`
-----------
我想这样,我怎么能请你帮助我。
我能用这个吗? :
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String date = sdf.format(calendar.getTime());
return date;
}
一个简单的方法,如果格式是你指向的格式,而不必担心转换日期如下:
int totalSum = getSecondsFromDate("05:12:02") + getSecondsFromDate("19:12:52") + getSecondsFromDate("40:12:14") + getSecondsFromDate("56:54:10") + getSecondsFromDate("41:12:12");
private int getSecondsFromDate(String date){
//We split the date to have hours, minutes and seconds
String splitDate = date.split(":");
int hours = Integer.parseInt(splitDate[0]);
int minutes = Integer.parseInt(splitDate[1]);
int seconds = Integer.parseInt(splitDate[2]);
int totalSeconds = (hours*60*60) + (minutes*60) + seconds;
return totalSeconds;
}
使用java.time中的Duration
类(现代Java日期和时间API):
String[] times = {
"05:12:02",
"19:12:52",
"40:12:14",
"56:54:10",
"41:12:12"
};
Duration timeSum = Duration.ZERO;
for (String time : times) {
// reformat to ISO 8601
time = time.replaceFirst("(\\d{2}):(\\d{2}):(\\d{2})", "PT$1H$2M$3S");
// add
timeSum = timeSum.plus(Duration.parse(time));
}
System.out.println("Total seconds: " + timeSum.getSeconds());
输出:
总秒数:585810
Duration
类不能直接解析你的时间字符串。它解析ISO 8601标准格式,因此我使用正则表达式将05:12:02
转换为PT05H12M02S
。然后我把它喂给Duration.parse
。您可以将ISO 8601字符串读作“05小时12分02秒的时间段”。
适用于日期和时间的课程 - Date
,Calendar
,LocalTime
等 - 适合一段时间。 Date
和Calendar
长期过时且设计不佳,所以不要尝试那些。虽然不可能通过,但也有一些陷阱,即使你成功了,也很难阅读代码并说服自己这是正确的。
是的,java.time
适用于较旧和较新的Android设备。它至少需要Java 6。
org.threeten.bp.Duration
运行的。org.threeten.bp
导入子包的日期和时间类。java.time
。java.time
首次被描述。java.time
的后端到Java 6和7(JST-310的ThreeTen)。