-1

I have a textfield in Java eclipse interface for which i want to validate it to accept only time format, but I don't want seconds included.

How do I validate it to accept only this format hh:mm but from hours 8:00 morning till 16:00 afternoon.

P.s TextField variable name is txtOra.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Lorik Berisha
  • 243
  • 1
  • 2
  • 20
  • 1
    Welcome on Stack Overflow. I recommend you to [take the tour](https://stackoverflow.com/tour) and read the [Help Center](https://stackoverflow.com/help) for information on asking a good and well-received question. You are missing a couple points there. – Ben May 28 '18 at 12:32
  • Which graphic framework are you using? Is it swing, awt, or maybe android? Are you sure it is `TextField` or maybe it is `JTextField` (these are not the same and solution may depend on it). – Pshemo May 28 '18 at 12:36
  • 1
    Possibly related: https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html, https://docs.oracle.com/javase/8/docs/technotes/guides/swing/1.4/ftf.html – Pshemo May 28 '18 at 12:39
  • [Check this](https://stackoverflow.com/questions/25873636/regex-pattern-for-exactly-hhmmss-time-string) Pattern: ```([8-9]|1[0-6]):([0-5][0-9])``` – Andry May 28 '18 at 12:40
  • This question has been asked and answered with variations many times. For example [Regex pattern for EXACTLY HH:MM:SS time String](https://stackoverflow.com/questions/25873636/regex-pattern-for-exactly-hhmmss-time-string). – Ole V.V. May 28 '18 at 13:04

3 Answers3

3

Just parse it with a DateTimeFormatter

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("H:mm");

LocalTime localTime = LocalTime.parse("16:16", dateTimeFormatter);

if parse does not throw an exception you have a valid time.

Then check for your constraints with LocalDate#isAfter and LocalDate#isBefore

Look it up here to find more patterns https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Zarathustra
  • 2,853
  • 4
  • 33
  • 62
1

If you are using java.time you can use LocalTime where you can use isBefore and isAfter like so :

public static boolean checkDateIsCorrect(String input){
    //Format your date
    LocalTime time = LocalTime.parse(input, DateTimeFormatter.ofPattern("H:mm"));
    //Then check if the time is between 8:00 and 16:00
    return !time.isBefore(LocalTime.parse("08:00")) 
                || !time.isBefore(LocalTime.parse("16:00"));
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

Use the following function to validate a time string with HH:MM (24 Hours Format)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public boolean validate(final String time){
      String TIME24HOURS_PATTERN = 
                "([01]?[0-9]|2[0-3]):[0-5][0-9]";
      Pattern pattern = Pattern.compile(TIME24HOURS_PATTERN);
      Matcher matcher = pattern.matcher(time);
      return matcher.matches();

}
nandal
  • 2,544
  • 1
  • 18
  • 23