This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How to parse the hours and mins string? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to parse the hours and mins string?" Watch "How to parse the hours and mins string?" New topic
Author

How to parse the hours and mins string?

divs saran
Greenhorn

Joined: Jan 09, 2008
Posts: 4
Hi,
How to parse string with hours and mins to mins? sample input strings are- 10 hours 30 mins, 1 hour, 2 hours, 45mins, 1 min. I have to convert the time to mins.
Any help is appreciated.
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874


divs,
first work out the format of the input String and use String's split() , subString() functions to get the numbers in them..
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37943
    
  22
Look for classes like SimpleDateFormat.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

That doesn't support using words like "hours" and "minutes".

I think regular expressions can help you out. You want the following:
1) a number, any number of spaces, the word "hours" - the number is the number of hours
2) a number, any number of spaces, the word "minutes" - the number is the number of minutes
3) a combination of the above two

One regular expression with two parts, each optional and each with a capturing group, could help you out quite easily - once you've set up the regex that is. Check out java.util.regex.Pattern and its full Javadoc page.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37943
    
  22
You can probably set up a group like hours|h|hr|hour|hrs to capture "hours" and similarly for minutes.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

And of course make it case insensitive.

<nitpicking>
hours|h|hr|hour|hrs is not optimal. You can optimize this by splitting of common parts (added parentheses and spaces to make it clearer):
That said, I would use your regex too. It may be suboptimal, but it's so much easier to understand.
</nitpicking>
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to parse the hours and mins string?
 
Similar Threads
What is the different between SCJP 5.0 and SCJP 5.0 Upgrade?
K&B MasterExam clarification
Question about my for loop
How many miles do you drive to work?
How to access content of p tag