1

I have an input field and the user may type time in different format(800,08:00,08:00 am etc).I need to display what ever the user input into a time format(xx:xx am/pm).

Example:

1.'800'=>'08:00';
2.'1245'=>'12:45';
3.'1000 am'=>'10:00 am';
4.'10.00 am'=>'10:00 am';
5.'9 am'=>'09:00 am';

So I could type in "800" and it would convert it to "8:00" or I could type in "2145" and it would convert it to "21:45".

I have tried with str.split(/[:;,. \/]/); ,but this is applicable only in the case of example 4.

0

2 Answers 2

3

You can use a regex to parse the string into its components:

var myregexp = /^(\d{1,2}?)\D?(\d{2})?\b\s*([ap]m)?$/;
var match = myregexp.exec(subject);
if (match != null) {
    hours = match[1];
    minutes = match[2];
    ampm = match[3];
} 

Explanation:

^         # Start of string
(         # Capture into group 1:
 \d{1,2}? # one or two digits, preferably one
)         # End of group 1
\D?       # Match an optional non-digit
(         # Capture into group 2:
 \d{2}    # Exactly two digits
)?        # End of (optional) group 2
\b        # End of number
\s*       # Optional whitespace
(         # Capture into group 3:
 [ap]m    # am or pm
)?        # End of (optional) group 3
$         # End of string

You can then use the results to construct a new, normalized string, which in this case means

  • adding a zero if the hours part is single-digit
  • adding 00 if the minutes part is undefined
  • deciding what to do if the am/pm part is undefined.

A regex can't do this part of the exercise since a regex can only match text that is present in the original string, not add to it dynamically.

Sign up to request clarification or add additional context in comments.

7 Comments

@TimPietzcker not working properly in the case of '9 am'.How will you change the regEx ?
@SujathanR: That wasn't part of the spec. What else isn't?
@TimPietzcker that's now in the spec,can you help me ?
@TimPietzcker what about if the input is '1020am' instead of '1020 am' ?
That also wasn't part of the spec. It seems you need to find out what you want first... you can replace the second \b with (?!\d), that should suffice to fix this immediate problem.
|
0

You cannot do this with a regular expression. You will need to write a function to apply some logic to the input string and decide what time to convert it to. Some of your possible inputs are

  • 4
  • 12:00 am
  • 1200
  • 12 am
  • 4:40
  • 4.40

etc. This needs to be done by you in a function.

1 Comment

I agree. Reg ex only works when you are sure of the input type or the Regular expression itself. Here both are variable. So you have to apply logic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.