timeparse.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. (function() {
  2. 'use strict';
  3. var timeParsePatterns = [
  4. // 9
  5. {
  6. re: /^\d{1,2}$/i,
  7. handler: function(bits) {
  8. if (bits[0].length === 1) {
  9. return '0' + bits[0] + ':00';
  10. } else {
  11. return bits[0] + ':00';
  12. }
  13. }
  14. },
  15. // 13:00
  16. {
  17. re: /^\d{2}[:.]\d{2}$/i,
  18. handler: function(bits) {
  19. return bits[0].replace('.', ':');
  20. }
  21. },
  22. // 9:00
  23. {
  24. re: /^\d[:.]\d{2}$/i,
  25. handler: function(bits) {
  26. return '0' + bits[0].replace('.', ':');
  27. }
  28. },
  29. // 3 am / 3 a.m. / 3am
  30. {
  31. re: /^(\d+)\s*([ap])(?:.?m.?)?$/i,
  32. handler: function(bits) {
  33. var hour = parseInt(bits[1]);
  34. if (hour === 12) {
  35. hour = 0;
  36. }
  37. if (bits[2].toLowerCase() === 'p') {
  38. if (hour === 12) {
  39. hour = 0;
  40. }
  41. return (hour + 12) + ':00';
  42. } else {
  43. if (hour < 10) {
  44. return '0' + hour + ':00';
  45. } else {
  46. return hour + ':00';
  47. }
  48. }
  49. }
  50. },
  51. // 3.30 am / 3:15 a.m. / 3.00am
  52. {
  53. re: /^(\d+)[.:](\d{2})\s*([ap]).?m.?$/i,
  54. handler: function(bits) {
  55. var hour = parseInt(bits[1]);
  56. var mins = parseInt(bits[2]);
  57. if (mins < 10) {
  58. mins = '0' + mins;
  59. }
  60. if (hour === 12) {
  61. hour = 0;
  62. }
  63. if (bits[3].toLowerCase() === 'p') {
  64. if (hour === 12) {
  65. hour = 0;
  66. }
  67. return (hour + 12) + ':' + mins;
  68. } else {
  69. if (hour < 10) {
  70. return '0' + hour + ':' + mins;
  71. } else {
  72. return hour + ':' + mins;
  73. }
  74. }
  75. }
  76. },
  77. // noon
  78. {
  79. re: /^no/i,
  80. handler: function(bits) {
  81. return '12:00';
  82. }
  83. },
  84. // midnight
  85. {
  86. re: /^mid/i,
  87. handler: function(bits) {
  88. return '00:00';
  89. }
  90. }
  91. ];
  92. function parseTimeString(s) {
  93. for (var i = 0; i < timeParsePatterns.length; i++) {
  94. var re = timeParsePatterns[i].re;
  95. var handler = timeParsePatterns[i].handler;
  96. var bits = re.exec(s);
  97. if (bits) {
  98. return handler(bits);
  99. }
  100. }
  101. return s;
  102. }
  103. window.parseTimeString = parseTimeString;
  104. })();