Shi*_*gon 74
根据Basil Bourque的评论,考虑到Java 8的新API,这是这个问题的更新答案:
String myDateString = "13:24:40";
LocalTime localTime = LocalTime.parse(myDateString, DateTimeFormatter.ofPattern("HH:mm:ss"));
int hour = localTime.get(ChronoField.CLOCK_HOUR_OF_DAY);
int minute = localTime.get(ChronoField.MINUTE_OF_HOUR);
int second = localTime.get(ChronoField.SECOND_OF_MINUTE);
//prints "hour: 13, minute: 24, second: 40":
System.out.println(String.format("hour: %d, minute: %d, second: %d", hour, minute, second));
Run Code Online (Sandbox Code Playgroud)
备注:
======以下是此问题的旧(原始)答案,使用pre-Java8 API:=====
我很抱歉,如果我对这个人感到不安,但我真的要回答这个问题.Java API非常庞大,我认为有人可能会偶尔错过一个.
SimpleDateFormat可以在这里做到这一点:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
它应该是这样的:
String myDateString = "13:24:40";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
//the above commented line was changed to the one below, as per Grodriguez's pertinent comment:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(myDateString);
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
int hour = calendar.get(Calendar.HOUR);
int minute; /... similar methods for minutes and seconds
Run Code Online (Sandbox Code Playgroud)
你应该知道的陷阱:
传递给SimpleDateFormat的模式可能与我示例中的模式不同,具体取决于您拥有的值(12小时格式或24小时格式的小时数等).请查看链接中的文档以获取详细信息
一旦你从你的String创建一个Date对象(通过SimpleDateFormat),不要试图使用Date.getHour(),Date.getMinute()等.它们似乎有时会工作,但总的来说它们会给出不好的结果,现在已经弃用了.请使用日历,如上例所示.
Joã*_*lva 10
有点冗长,但它是在Java中解析和格式化日期的标准方法:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
String time = "12:32:22";
String[] values = time.split(":");
Run Code Online (Sandbox Code Playgroud)
这会花费你一些时间,并在看到冒号的地方将其拆分,并将值放入数组中,因此此后你应该有 3 个值。
然后循环遍历字符串数组并转换每一个。(和Integer.parseInt)