2012-01-18 23 views
0

我几乎完成了代码,但仍需要一些帮助。此代码基于将minutes添加到startTime来计算newTime。该minutes可能值大于60的问题是,在当前例如,它必须输出“00:10”,但它输出“23:70” ......将更多分钟添加到“HH:MM”字符串的代码

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); 
+2

[转换整数分钟到字符串 “HH:MM”]可能重复(HTTP:/ /stackoverflow.com/questions/8916472/convert-integer-minutes-into-string-hhmm) – 2012-01-18 21:18:33

+0

Jon Skeet comment = +1! – eboix 2012-01-18 21:19:50

+0

为什么你有代码来处理负面分钟? “00:-1”是否有意义?如果是的话,你可以有'-1:00'吗?或'-1:-1'? – 2012-01-18 21:21:22

回答

1

我建议计算总数

String startTime = "23:40"; 
int minutes = 30; 

String[] hm = startTime.split(":"); 
int h = Integer.parseInt(hm[0]); 
int m = Integer.parseInt(hm[1]); 

int t = h * 60 + m;  // total minutes 
t += minutes;   // add the desired offset 

while (t < 0) {   // fix `t` so that it's never negative 
    t += 1440;    // 1440 minutes in a day 
} 

int nh = (t/60) % 24; // calculate new hours 
int nm = t % 60;   // calculate new minutes 

String newTime = String.format("%02d:%02d", nh, nm); 

你绝对不应来增加你的minutes变量的计算:自午夜开始作为一个单一的值,然后加入所需数量,然后重新计算得到的小时和分钟分钟- 它们是不兼容的单位。

2

如何:

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

相关问题