html5 поле ввода даты с временем
Дата и время в HTML. Формат, текущее время, часы на сайте
При работе с датой и временем на сайте есть необходимость в том, чтобы суть содержимого понимали как пользователи сайта, так и роботы (поисковые системы, скрипты и т.п).
Для человека будет достаточно написать «сегодня в 10», «через 3 дня», в «прошлом году», но для «машины» такая запись далеко не всегда будет информативной. Формат даты и времени в HTML позволяет описывать выражения подобные этим, а также указывать не только временные точки, но и временные отрезки, например «длительность 2 часа 17 минут».
Рассмотрим как правильно писать дату и время в HTML.
Формат точной даты и времени YYYY-MM-DDThh:mm:ssTZD
Этот формат используется для указания конкретной временной точки («20-го апреля», «сегодня в 8 утра», «15 января 2001 года»).
В зависимости от потребностей вы можете использовать как все составляющие, так и какую-то их часть.
Расшифровка формата YYYY-MM-DDThh:mm:ssTZD:
Рассмотрим примеры вывода даты и времени в формате временной точки.
Название | Формат | Пример |
---|---|---|
Дата, точное время, временная зона | YYYY-MM-DDThh:mm:ssTZD | 2010-05-12 22:47:11+02:00 |
Дата и время | YYYY-MM-DDThh:mm | 2015-09-23 21:13 |
Время с временной зоной | hh:mmTZD | 12:34+04:00 |
Дата | YYYY-MM-DD | 2015-09-23 |
Месяц и число | MM-DD | 01-30 |
Год и месяц | YYYY-MM | 1989-11 |
Год и неделя | YYYY-WW | 2009-46 |
Год | YYYY | 2007 |
Формат периода времени (длительность)
Формат PWDTHMS используется когда нужно указать не конкретную точку, а период времени: «3 дня», «2 часа 5 минут» и т.п. То есть, когда нужно показать длительность.
Длительность периода считается в секундах. Если указана другая величина, время приводится к секундам путем умножения:
2 минуты = 2*60 = 120 секунд и т.п.
Расшифровка формата PWDTHMS:
Примеры указания периода времени:
Название | Формат | Пример |
---|---|---|
2 недели | PхW | P2W |
10 дней | PхD | P10D |
4 дня 3 часа 5 минут | PхDTхHхM | P4DT3H5M |
2 часа 37 минут | PTхHхM | PT2H37M |
5 минут 10 секунд | PTхMхS | PT5M10S |
Как вставить текущее время в HTML
Вывести на страницу сайта текущее время используя только лишь HTML не получится.
Для того, чтобы вставить текущую дату и время на сайт будем использовать JavaScript.
Попробуем вывести текущую дату и время на экран с помощью встроенного скрипта:
Как видим, выводится вся информация о дате и времени.
Дата и время в HTML в привычном формате
Поскольку функции возвращают значения месяцев, дней, часов, минут, секунд без ведущих нулей, нам понадобится написать дополнительную функцию, которая будет эти нули добавлять.
Также обратите внимание на то, что функция getMonth() возвращает значение от 0 до 11 (количество полных месяцев, прошедших от начала года до указанной даты), а не порядковый номер месяца от 1 до 12. Поэтому, чтобы получить календарный номер месяца нужно к результату функции прибавить единицу.
Вставить текущее время и дату в HTML в привычном формате можно с помощью следующего кода:
Таким образом у нас получилось вывести на страницу сайта точное время на момент открытия страницы.
Часы на сайт, обновляемые в реальном времени
Если мы хотим, чтобы пользователь всегда видел актуальное время, то есть хотим сделать часы на странице, нужно реализовать обновление времени один раз в секунду (либо в минуту, если вы не выводите секунды). Для этого воспользуемся интервалом в JavaScript.
Html5 поле ввода даты с временем
элемент типа datetime-local создаёт поля ввода, позволяющие легко ввести дату и время — год, месяц, день, часы и минуты.
Для тех из вас, кто не использует поддерживающий браузер, Chrome/Opera datetime-local control выглядит как скриншот ниже. Нажатие на стрелку вниз с правой стороны приводит к выбору даты, чтобы вы могли выбрать дату; вы должны ввести время вручную.
Значение
DOMString представление значения даты, введённой во входные данные. Вы можете установить значение по умолчанию для ввода, включая дату внутри value атрибута, как:
Вы также можете получить и установить значение даты в JavaScript, используя HTMLInputElement.value свойство, например:
Использование локальных входных данных datetime
Ввод даты и времени выглядит удобно на первый взгляд — он обеспечивает простой пользовательский интерфейс для выбора даты и времени, и они нормализуют формат данных, отправляемых на сервер, независимо от локали пользователя. Тем не менее, есть проблемы с из-за ограниченной поддержки браузера.
Базовое использование локальных полей ввода datetime
Самое простои использование включает комбинацию базового и элемента, как в примере ниже:
Установка максимума и минимума даты и времени
Вы можете использовать min и max атрибуты чтобы ограничить дату/время, которое может выбрать пользователь. В примере ниже мы устанавливает минимальные дату и время в 2017-06-01T08:30 и максимальные в 2017-06-30T16:30 :
Примечание: Существует возможность использовать step атрибут для того, чтобы установить количество дней, которые будут пропущены каждый раз, когда дата увеличивается (например, если вы хотите сделать доступными для выбора только Субботы). Однако, на момент написание этой статьи это нет эффективной реализации этой функции.
Controlling input size
Setting timezones
One thing the datetime-local input type doesn’t provide is a way to set the timezone/locale of the datetime. This was available in the datetime input type, but this type is now obsolete, having been removed from the spec. The main reasons why this was removed are a lack of implementation in browsers, and concerns over the user interface/experience. It is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control.
For example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in a hidden input type. For example:
On the other hand, if you were required to allow the user to enter a timezone along with a datetime entry, you could provide a means of inputting a timezone, such as a element:
In either case, the timedate and timezone values would be submitted to the server as separate data points, and then you’d need to store them appropriately in the database on the server-side.
Note: The above code snippet is taken from All world timezones in an HTML select element.
Validation
By default, does not apply any validation to entered values. The UI implementations generally don’t let you enter anything that isn’t a datetime — which is helpful — but you can still fill in no value and submit, or enter an invalid datetime (e.g. the 32th of April).
You can use min and max to restrict the available dates (see anch(«Setting maximum and minimum dates»)), and in addition use the required attribute to make filling in the date mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field.
Let’s look at an example — here we’ve set minimum and maximum datetimes, and also made the field required:
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here’s’a screenshot for those of you who aren’t using a supporting browser:
Here’s the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can’t be styled or shown effectively.
Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).
Handling browser support
As mentioned above, the major problem with using date inputs at the time of writing is browser support — only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile. As an example, the datetime-local picker on Firefox for Android looks like this:
Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
One way around this is to put a pattern attribute on your datetime-local input. Even though the datetime-local input doesn’t use it, the text input fallback will. For example, try viewing the following demo in a non-supporting browser:
And what user is going to understand the pattern they need to enter the time and date in?
We still have a problem.
The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, year, and time in separate controls ( elements being popular — see below for an implementation), or use JavaScript libraries such as jQuery date picker, and the jQuery timepicker plugin.
Examples
In this example we create two sets of UI elements for choosing datetimes — a native picker, and a set of five elements for choosing dates and times in older browsers that don’t support the native input.
The HTML looks like so:
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year respectively (see the code comments below for detailed explanations of how these functions work.) We also decided to dynamically generate the hours and months, as there are so many of them!
Html5 поле ввода даты с временем
Элементы типа date создают поля ввода и позволяют пользователю ввести дату, либо использовать text box для автоматической проверки контента или использовать специальный интерфейс date picker. Возвращаемое значение включает год, месяц, день, но не время. Используйте поля ввода time (en-US) или datetime-local, чтобы вводить время или дату+время соответственно.
Исходный код этого интерактивного примера хранится в репозитории GitHub. Если вы хотите внести свой вклад в проект интерактивных примеров, пожалуйста, клонируйте https://github.com/mdn/interactive-examples и отправьте нам запрос на внесение изменений.
Среди браузеров со своим интерфейсом для выбора даты, есть интерфейс браузеров Chrome и Opera, который выглядит так:
В Edge он выглядит так:
А в Firefox выглядит так:
Значение
Вы также можете получить или установить значение даты в JavaScript с помощью свойств value и valueAsNumber элемента input. Например:
Дополнительные атрибуты
Атрибут | Описание |
---|---|
max | Максимально возможная дата для установки |
min | Минимально возможная дата для установки |
step | Шаг (в днях), с которым будет изменяться дата при нажатии кнопок вниз или вверх данного элемента |
Строковое значение any означает, что никакое значение шага не задано и допустимо любое значение (в пределах других ограничений, таких как min и max ).
Примечание: Когда значение, введённое пользователем, не подходит под заданное значение шага, user agent может округлить его до ближайшего допустимого значения с приоритетом в большую сторону в том случае, если значение находится ровно посередине шага.
Для полей ввода date значение step задаётся в днях; и является количеством миллисекунд, равное 86 400 000 умножить на значение step (получаемое числовое значение хранится в миллисекундах). Стандартное значение step равно 1, что означает 1 день.
Использование полей ввода c типом date
На первый взгляд, элемент выглядит заманчиво — он предоставляет лёгкий графический интерфейс для выбора даты, нормализует формат даты, отправляемой на сервер независимо от локальных настроек пользователя. Тем не менее, есть проблемы с в связи с ограниченной поддержкой браузеров.
Надеемся, со временем поддержка браузерами станет повсеместной, и эта проблема исчезнет.
Как использовать date?
Установка максимальной и минимальной даты
В результате выполнения кода, пользователь сможет выбрать любой день апреля 2017 года, но не сможет выбрать и даже просмотреть дни других месяцев и годов, в том числе через виджет date picker.
Controlling input size
Validation
By default, does not apply any validation to entered values. The UI implementations generally don’t let you enter anything that isn’t a date — which is helpful — but you can still leave the field empty or (in browsers where the input falls back to type text ) enter an invalid date (e.g. the 32nd of April).
If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you’ll have to check the results to be sure the value is within these dates, since they’re only enforced if the date picker is fully supported on the user’s device.
In addition, you can use the required attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.
Let’s look at an example — here we’ve set minimum and maximum dates, and also made the field required:
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here’s a screenshot for those of you who aren’t using a supporting browser:
Here’s the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can’t be styled or shown effectively.
Important: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).
Handling browser support
As mentioned above, the major problem with using date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:
Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
One way around this is to put a pattern attribute on your date input. Even though the date input doesn’t use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:
The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls ( elements being popular; see below for an implementation), or to use a JavaScript library such as jQuery date picker.
Examples
In this example we create two sets of UI elements for choosing dates: a native picker and a set of three elements for choosing dates in older browsers that don’t support the native input.
The HTML looks like so:
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)
JavaScript
Note: Remember that some years have 53 weeks in them (see Weeks per year)! You’ll need to take this into consideration when developing production apps.