Reputation: 5805
Assuming that time formats (not timezone data, just plain-text Strings representing time in 12-hour clock), what is the best way to parse that data (examples below)?
I feel like this is a pretty simple question, but I've though about it a lot and can't figure out a fool-proof process for parsing out hour
and minute
values from any one of many time "formats".
I'm using a simple form that allows for entering a time (e.g., the time of a reservation), but there is no way to make the form field (Google Forms, limited customizability) anything other than plain-text which allows for any time format a person wishes to put in there a viable piece of data to work with. Here are some examples of times that can be entered:
1 P // hours would be 13, minutes would be 0
3:15 P.M. // hours would be 15, minutes would be 15
4 P.M // hours would be 16, minutes would be 0
8:30 a // hours would be 8, minutes would be 30
10:45 aM. // hours would be 10, minutes would be 45
12:00 Pm // hours would be 12, minutes would be 0
Those are just some examples. Feel free to fix tags if I'm not in the right topic(s) - I am however using Google Apps Script/Javascript to accomplish this.
I thought about building a couple regex strings to look for certain formats (which I'm sure will take me a while to write since I've never written one before).
I also thought about looking for a ':' character, and an 'a'/'A' character or 'p'/'P' for determing whether or not the +12 hours needs to be added. After that kind of information is retrieved the problem could be solved by truncating the 'p.m.'-type sections, then split(":")
to get the correct numbers.
I feel like the first approach is much more stable, but the second solution might be easier. I'm not sure if there is a better way though, those are the two methods my n00b programmer mind could come up with.
Upvotes: 0
Views: 165
Reputation: 45750
I'm glad to hear you have an answer that you think will help you out. But before you write too much code, revisit this assertion you made:
...there is no way to make the form field (Google Forms, limited customizability) anything other than plain-text
Here's how you define a question to present a Date & Time picker, using the Forms UI.
The spreadsheet that is receiving your form responses will end up with a Date object - no need to mess around with strings at all.
Upvotes: 1