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?
Description. The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.
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:
====== 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With