48

How can I parse a time of format hh:mm:ss , inputted as a string to obtain only the integer values (ignoring the colons) in java?

mkobit
  • 34,772
  • 9
  • 135
  • 134
user1604288
  • 655
  • 1
  • 5
  • 7
  • 6
    Welcome to Stack Overflow! We encourage you to [research your questions](http://stackoverflow.com/questions/how-to-ask). If you've [tried something already](http://whathaveyoutried.com/), please add it to the question- if not, research and attempt your question first, and then come back. – David B Aug 16 '12 at 20:14
  • So far, I have the user input the time as a string and that's it. I have done a fairly large amount of research but because I'm so new to programming it is hard to make sense out of what people say – user1604288 Aug 16 '12 at 20:16
  • 5
    [`java.text.SimpleDateFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) – Sebastian Paaske Tørholm Aug 16 '12 at 20:17
  • Something similar to get you started here: http://stackoverflow.com/questions/950409/how-to-parse-this-string-in-java – vector Aug 16 '12 at 20:20
  • 2
    You might take a look at the SO [FAQ] and [Ask] to get a better sense of what types of questions are appropriate here. – Jim Garrison Aug 16 '12 at 20:21
  • 1
    Try to write your question the way you feel. People will comment (maybe edit) your question in order to help you. Remember, it's better to ask a *silly* question that stay all quiet (because some silly questions can be answered with "you're wrong"). – Luiggi Mendoza Aug 16 '12 at 20:29
  • 3
    Found this with google, and it has exactly the question I was asking and exactly the answer I was looking for. If that isn't Stack Overflow, I don't know what is. – Kevin S. Aug 29 '14 at 19:47
  • 1
    This question was just what I was looking for. Maybe not perfectly phrased but so what, it solved my problem! – Blisterpeanuts Feb 25 '16 at 20:03

4 Answers4

79

As per Basil Bourque's comment, this is the updated answer for this question, taking into account the new API of Java 8:

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

Remarks:

  • since the OP's question contains a concrete example of a time instant containing only hours, minutes and seconds (no day, month, etc.), the answer above only uses LocalTime. If wanting to parse a string that also contains days, month, etc. then LocalDateTime would be required. Its usage is pretty much analogous to that of LocalTime.
  • since the time instant int OP's question doesn't contain any information about timezone, the answer uses the LocalXXX version of the date/time classes (LocalTime, LocalDateTime). If the time string that needs to be parsed also contains timezone information, then ZonedDateTime needs to be used.

====== Below is the old (original) answer for this question, using pre-Java8 API: =====

I'm sorry if I'm gonna upset anyone with this, but I'm actually gonna answer the question. The Java API's are pretty huge, I think it's normal that someone might miss one now and then.

A SimpleDateFormat might do the trick here:

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

It should be something like:

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

The gotchas you should be aware of:

  • the pattern you pass to SimpleDateFormat might be different then the one in my example depending on what values you have (are the hours in 12 hours format or in 24 hours format, etc). Look at the documentation in the link for details on this

  • Once you create a Date object out of your String (via SimpleDateFormat), don't be tempted to use Date.getHour(), Date.getMinute() etc. They might appear to work at times, but overall they can give bad results, and as such are now deprecated. Use the calendar instead as in the example above.

Shivan Dragon
  • 14,526
  • 9
  • 54
  • 96
12

A bit verbose, but it's the standard way of parsing and formatting dates in 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();
}
João Silva
  • 81,431
  • 26
  • 144
  • 151
  • Except that silently swallowing exceptions is rarely a great option. Makes it hard to find out what went wrong, when something goes wrong. – yshavit Aug 16 '12 at 20:35
  • 3
    @yshavit: It was merely an example. – João Silva Aug 16 '12 at 21:16
  • I understand, but given that the OP is a self-proclaimed beginner, I wanted them to understand that that part of the example is not something they should take literally. – yshavit Aug 16 '12 at 21:21
  • to make yshavit happy: JOptionPane.showMessageDialog(null, e); – Petro Dec 06 '13 at 19:47
  • Update: it *was* the standard way of parsing and formatting a time in Java until 2014. – Ole V.V. Mar 22 '20 at 04:36
3
String time = "12:32:22";
String[] values = time.split(":");

This will take your time and split it where it sees a colon and put the value in an array, so you should have 3 values after this.

Then loop through string array and convert each one. (with Integer.parseInt)

yshavit
  • 39,951
  • 7
  • 75
  • 114
AwDogsGo2Heaven
  • 902
  • 10
  • 25
1

If you want to extract the hours, minutes and seconds, try this:

String inputDate = "12:00:00";
String[] split = inputDate.split(":");
int hours = Integer.valueOf(split[0]);
int minutes = Integer.valueOf(split[1]);
int seconds = Integer.valueOf(split[2]);
aymeric
  • 3,784
  • 2
  • 25
  • 42