This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to parse the hours and mins string?

 
divs saran
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look for classes like SimpleDateFormat.
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can probably set up a group like hours|h|hr|hour|hrs to capture "hours" and similarly for minutes.
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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>
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic