Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

How to parse the hours and mins string?

 
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.
 
Ranch Hand
Posts: 874
Android VI Editor Java
  • 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..
 
Marshal
Posts: 69894
278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look for classes like SimpleDateFormat.
 
Sheriff
Posts: 21974
106
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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
Marshal
Posts: 69894
278
  • 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
Posts: 21974
106
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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>
 
    Bookmark Topic Watch Topic
  • New Topic