java校验时间格式 HH:MM

时间:2021-02-11 17:33:48
  1. package com;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. /**
  5. * @author Gerrard
  6. */
  7. public class CheckTimeHHMM {
  8. public static void main(String[] args) {
  9. boolean flg = checkTime("8:00");
  10. boolean flg3 = checkTime("24:00");
  11. boolean flg1 = checkTime("8:60");
  12. boolean flg2 = checkTime("25:00");
  13. boolean flg4 = checkTime("25:0-");
  14. boolean flg6 = checkTime("ss:0-");
  15. if (flg) {
  16. System.out.println("8:00是正确格式");
  17. }
  18. if (flg3) {
  19. System.out.println("24:00是正确格式");
  20. }
  21. if (!flg1) {
  22. System.out.println("8:60不是正确格式");
  23. }
  24. if (!flg2) {
  25. System.out.println("25:00不是正确格式");
  26. }
  27. if (!flg4) {
  28. System.out.println("25:0-不是正确格式");
  29. }
  30. if (!flg6) {
  31. System.out.println("ss:0-不是正确格式");
  32. }
  33. }
  34. /**
  35. * 校验时间格式(仅格式)
  36. */
  37. public static boolean checkHHMM(String time) {
  38. SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
  39. try {
  40. @SuppressWarnings("unused")
  41. Date t = dateFormat.parse(time);
  42. }
  43. catch (Exception ex) {
  44. return false;
  45. }
  46. return true;
  47. }
  48. /**
  49. * 校验时间格式HH:MM(精确)
  50. */
  51. public static boolean checkTime(String time) {
  52. if (checkHHMM(time)) {
  53. String[] temp = time.split(":");
  54. if ((temp[0].length() == 2 || temp[0].length() == 1) && temp[1].length() == 2) {
  55. int h,m;
  56. try {
  57. h = Integer.parseInt(temp[0]);
  58. m = Integer.parseInt(temp[1]);
  59. } catch (NumberFormatException e) {
  60. return false;
  61. }
  62. if (h >= 0 && h <= 24 && m <= 60 && m >= 0) {
  63. return true;
  64. }
  65. }
  66. }
  67. return false;
  68. }
  69. }