从时间字符串中读取小时和分钟

时间:2014-01-05 18:11:11

标签: java string int

有一个问题String有“:”

 String time = "21:45";

如何将此字符串转换为两个int:

int hour = 21;
int minute = 45;

4 个答案:

答案 0 :(得分:5)

直接前进,非验证方式:

String[] parts = time.split(":");
int hour = Integer.parseInt(parts[0]);
int minute = Integer.parseInt(parts[1]);

答案 1 :(得分:3)

您应该考虑使用Calendar来解析这样的时间字符串:

String time = "21:45";

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setLenient(false);  
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(time));

int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

System.out.println(hour);
System.out.println(minute);
21
45

您可以处理潜在的ParseException来处理无效的输入。

答案 2 :(得分:1)

这是一个真正有效的解决方案:

String time = "21:45";

boolean valid = true;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
sdf.setLenient(false); // important for validation

GregorianCalendar gcal = new GregorianCalendar();
try {
  gcal.setTime(sdf.parse(time));
} catch (ParseException pe) {
  valid = false;
}

if (valid) {
  int hours = gcal.get(Calendar.HOUR_OF_DAY);
  int minutes = gcal.get(Calendar.MINUTE);
  System.out.println("Hours: " + hours);
  System.out.println("Minutes: " + minutes);
} else {
  System.out.println("Sorry, the input is not valid: " + time);
}

答案 3 :(得分:0)

试试这个:

  String arr[]= time.split(":", 2);
  int num1 = Integer.parseInt(arr[0]);
  int num2 = Integer.parseInt(arr[1]);