我几乎完成了代码,但我仍然需要一些帮助。此代码通过将 分钟
添加到 startTime
来计算 newTime
。分钟的值可能大于 60。问题是在当前示例中它必须输出“00:10”,但它输出“23:70”...
String startTime = "23:40";
int minutes = 30;
String[] hm = startTime.split(":");
int h = minutes / 60 + Integer.parseInt(hm[0]);
int m = minutes % 60 + Integer.parseInt(hm[1]);
if (m<0) {
if (h==0)
h=23;
else
h = h-1;
m = 60+m;
}
String newTime = String.format("%02d", h)+":"+String.format("%02d", m);
System.out.println(newTime);
最佳答案
怎么样:
import java.util.*;
import java.util.regex.*;
...
String startTime = "23:40";
int additionalMinutes = 30;
Pattern pat = Pattern.compile( "(\\d+):(\\d+)" );
Matcher x = pat.matcher(startTime);
if (x.matches())
{
int h = Integer.parseInt(x.group(1));
int m = Integer.parseInt(x.group(2));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, h);
cal.set(Calendar.MINUTE, m);
cal.add(Calendar.MINUTE, additionalMinutes);
h = cal.get(Calendar.HOUR);
m = cal.get(Calendar.MINUTE);
System.out.println(
"Start: " + startTime +
" + " + additionalMinutes + " minutes = " +
h + ":" + m );
}
else
{
/* bad format */
}
输出:开始:23:40 + 30 分钟 = 0:10
关于java - 用于向 "HH:MM"字符串添加更多分钟的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8917551/