I need to validate a textBox entry which contains time.
Time should be in HH:mm format and in 24-hour format.
For eg:
09:00, 21:00, 00:00, etc.,
Invalid entries:
2534, 090, *7&**, etc.,
If time entered is in HHmm format, then I need to append a ':' to the entry.
For e.g:
If textBox entry= 0930, it should be changed to 09:30
This is what I have so far:
String textBoxVal = getTextBoxValue();
String colonCheck = ":";
if (!textBoxVal.contains(colonCheck)){
textBoxVal = textBoxVal.substring(0,2) + ":" + textBoxVal.substring(2,4);
}
But as is obvious, this code isn't going to work for all cases.
I'm not very familiar with regex, so any help on how this can be achieved using regex in Java, would be helpful!Thanks!
Solution using DateFormat, as pointed by Ranhiru
String theTime = "23:55";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); //HH = 24h format
dateFormat.setLenient(false); //this will not enable 25:67 for example
try {
System.out.println(dateFormat.parse(theTime));
} catch (ParseException e) {
throw new RuntimeException("Invalid time "+theTime, e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With