我有两个字符串时间
1:30:00
1:35:00
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法来添加这两次并获得一个新的时间应该是什么
3:05:00?
我想在客户端这样做,所以如果我可以避免任何日期的liabraries
请记住,您可以将小时/分钟/秒的int值转换为单个int,如下所示:
int totalSeconds = ((hours * 60) + minutes) * 60 + seconds;
Run Code Online (Sandbox Code Playgroud)
并转换回来:
int hours = totalSeconds / 3600; // Be sure to use integer arithmetic
int minutes = ((totalSeconds) / 60) % 60;
int seconds = totalSeconds % 60;
Run Code Online (Sandbox Code Playgroud)
或者你可以按如下方式逐步进行算术:
int totalHours = hours1 + hours2;
int totalMinutes = minutes1 + minutes2;
int totalSeconds = seconds1 + seconds2;
if (totalSeconds >= 60) {
totalMinutes ++;
totalSeconds = totalSeconds % 60;
}
if (totalMinutes >= 60) {
totalHours ++;
totalMinutes = totalMinutes % 60;
}
Run Code Online (Sandbox Code Playgroud)
String time1="0:01:30";
String time2="0:01:35";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date1 = timeFormat.parse(time1);
Date date2 = timeFormat.parse(time2);
long sum = date1.getTime() + date2.getTime();
String date3 = timeFormat.format(new Date(sum));
System.out.println("The sum is "+date3);
Run Code Online (Sandbox Code Playgroud)
Ouput: The sum is 00:03:05
| 归档时间: |
|
| 查看次数: |
13607 次 |
| 最近记录: |