regex - Parsing user time input in Java/GWT -


what best way parse time user typed in text field in gwt? default time formats require users enter time time format locale specifies it.

i want more flexible there many different ways users can enter time. example, entries "8", "8p", "8pm", "8.15pm", "13:15", "1315", "13.15" should valid.

i ended own method want share. method returns time in milliseconds, can displayed using data formats selected locale.

any suggestions improve highly appreciated.

edit: improved following suggestions in comments.

public static long parsetime(string value) {      // ";" common typo - not punishing users     value = value.trim().tolowercase().replace(";", ":");      regexp time12 = regexp.compile("^(1[012]|[1-9])([:.][0-5][0-9])?(\\s)?(a|p|am|pm)?$");     regexp time24 = regexp.compile("^(([01]?[0-9]|2[0-3])[:.]?([0-5][0-9])?)$");      if (time12.test(value) || time24.test(value)) {          string hours = "0", minutes = "0";          if (value.contains(":") || value.contains(".")) {             string[] values = value.split("[:.]");             hours =  values[0];             minutes = values[1].substring(0, 2);         } else {             // process strings "8", "8p", "8pm", "2300"             if (value.contains("a")) {                 hours = value.substring(0, value.indexof("a")).trim();             } else if (value.contains("p")) {                 hours = value.substring(0, value.indexof("p")).trim();             } else if (value.length() < 3) {                 hours = value;             } else {                 hours =  value.substring(0, value.length() - 2);                 minutes = value.substring(value.length() - 2);             }         }         if (value.contains("a") && hours.equals("12")) {             // 12am 0 hours             hours = "0";         }          long time = (long.valueof(hours) * 60 + long.valueof(minutes)) * 60 * 1000;          if (value.contains("p") && !hours.equals("12")) {             // "pm" adds 12 hours total, except 12pm             time += 12 * 60 * 60 * 1000;         }          return time;     }     return null; } 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -