htmltimemaxmin

HTML Input Time, where min is pm (late) and max is am (early)


I have an input box, with a type of "time". I want to have a late time (23:00pm) as a min value, and an early time (6:00am) as a max value - creating a range of 23pm - 6am. (ie. 11pm, 12pm, 1am, 2am, 3am, 4am, 5am, 6am).

I've tried using Javascript, although I want to use it as a last resort. I don't want the native component to show up with values that I don't want the user to select (for example, on mobile devices).

Setting the 'min' value to 00:00:00 and the 'max' value to "06:00:00" works as intended. It's when the min value is before midnight it becomes an issue.

I'd expect the min and max values to create a range, but that doesn't work as expected.


Solution

  • As stated in MDN docs:

    Unlike many data types, time values have a periodic domain, meaning that the values reach the highest possible value, then wrap back around to the beginning again. For example, specifying a min of 14:00 and a max of 2:00 means that the permitted time values start at 2:00 PM, run through midnight to the next day, ending at 2:00 AM.

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#max

    That said, it seems like this is not working properly in Chrome 76.0, after a simple test with a min value greater than the max, all times fail the validation and the form just don't work.

    I suggest https://timepicker.co/ since it will work cross browser.

    input:invalid+.validity:after {
      content: '✖';
    }
    
    input:valid+.validity:after {
      content: '✓';
    }
    <form>
      <label for="time1">3:00 to 6:00: </label>
      <input type="time" min="3:00" max="6:00" name="time1" required>
      <span class="validity"></span>
      <hr>
      <label for="time2">23:00 to 6:00: </label>
      <input type="time" min="23:00" max="6:00" name="time2" required>
      <span class="validity"></span>
    </form>