- Firefox datetime local не работает
- Значение
- Использование локальных входных данных datetime
- Базовое использование локальных полей ввода datetime
- Установка максимума и минимума даты и времени
- Controlling input size
- Setting timezones
- Validation
- Handling browser support
- Examples
- Firefox datetime local не работает
- Value
- Additional attributes
- Using datetime-local inputs
- Basic uses of datetime-local
- Setting maximum and minimum dates and times
- Controlling input size
- Setting timezones
- Validation
- Handling browser support
- The Y2K38 Problem (often server-side)
- The Y10k Problem (often client-side)
- Examples
Firefox datetime local не работает
элемент типа datetime-local создаёт поля ввода, позволяющие легко ввести дату и время — год, месяц, день, часы и минуты.
Интерфейс управления варьируется от браузера к браузеру, на данный момент поддержка носит фрагментарный характер, только с Chrome/Opera и EDGE на рабочем столе — и большинство современных мобильных версиях браузера — наличие полезной реализации. В других браузерах элемент управления сводиться до простого .
Для тех из вас, кто не использует поддерживающий браузер, Chrome/Opera datetime-local control выглядит как скриншот ниже. Нажатие на стрелку вниз с правой стороны приводит к выбору даты, чтобы вы могли выбрать дату; вы должны ввести время вручную.
В Edge datetime-local элемент управления выглядит как на скриншоте ниже. Клик на дате и времени отобразит два отдельных поля выбора, чтобы вы могли легко установить дату и время. То есть, по сути, получаем два элемента date и time , объединённых в один:
Value | A DOMString representing a date and time, or empty. |
события | change (en-US) и input (en-US) . |
Supported Common Attributes | autocomplete , list , readonly , and step . |
IDL attributes | list , value , valueAsNumber . |
методы | select() (en-US) , stepDown() (en-US) , stepUp() (en-US) . |
Значение
DOMString представление значения даты, введённой во входные данные. Вы можете установить значение по умолчанию для ввода, включая дату внутри value атрибута, как:
Одна вещь, чтобы отметить, что отображаемый формат даты отличается от фактического значения — отображаемый формат даты будет выбран на основе установленного языкового стандарта операционной системы пользователя, в то время как дата значение всегда форматируется yyyy-MM-ddThh:mm . Когда значение передаётся на сервер, например, это будет выглядеть partydate=2017-06-01T08:30 .
Примечание: также имейте в виду, что если такие данные поступают через http-запрос Get, двоеточие нужно экранировать для включения в параметры URL, например partydate=2017-06-01T08%3A30 .
Вы также можете получить и установить значение даты в JavaScript, используя HTMLInputElement.value свойство, например:
Использование локальных входных данных datetime
Ввод даты и времени выглядит удобно на первый взгляд — он обеспечивает простой пользовательский интерфейс для выбора даты и времени, и они нормализуют формат данных, отправляемых на сервер, независимо от локали пользователя. Тем не менее, есть проблемы с из-за ограниченной поддержки браузера.
Мы рассмотрим основные и более сложные способы использования , затем предложим советы по устранению проблемы поддержки браузера позже (see Handling browser support).
Базовое использование локальных полей ввода datetime
Самое простои использование включает комбинацию базового и элемента, как в примере ниже:
Установка максимума и минимума даты и времени
Вы можете использовать min и max атрибуты чтобы ограничить дату/время, которое может выбрать пользователь. В примере ниже мы устанавливает минимальные дату и время в 2017-06-01T08:30 и максимальные в 2017-06-30T16:30 :
- Могут быть выбраны только дни из Июня 2017 — только дни, которые входят в заданный диапазон дат доступны для выбора, и в виджете нельзя увидеть даты, не принадлежащие Июню.
- В зависимости от того, какой браузер вы используете, вы можете заметить, что время вне заданного диапазона не доступно к выбору (e.g. Edge), или доступно к выбору(e.g. Chrome) но невалидно (see Validation).
Примечание: Существует возможность использовать step атрибут для того, чтобы установить количество дней, которые будут пропущены каждый раз, когда дата увеличивается (например, если вы хотите сделать доступными для выбора только Субботы). Однако, на момент написание этой статьи это нет эффективной реализации этой функции.
Controlling input size
doesn’t support form sizing attributes such as size . You’ll have to resort to CSS for sizing needs.
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.
The second problem is the most serious — as we mentioned earlier, with a datetime-local input the actual value is always normalized to the format yyyy-mm-ddThh:mm . With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates and times, for example:
- ddmmyyyy
- dd/mm/yyyy
- mm/dd/yyyy
- dd-mm-yyyy
- mm-dd-yyyy
- mm-dd-yyyy hh:mm (12 hour clock)
- mm-dd-yyyy hh:mm (24 hour clock)
- etc.
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:
If you try submitting it, you’ll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn’t match the pattern nnnn-nn-nnTnn:nn , where n is a number from 0 to 9. Of course, this doesn’t stop people from entering invalid dates, or incorrectly formatted dates and times.
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!
The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports , we create a new element, set its type to date , then immediately check what its type is set to — non-supporting browsers will return text , because the date type falls back to type text . If is not supported, we hide the native picker and show the fallback picker UI ( ) instead.
Источник
Firefox datetime local не работает
elements of type datetime-local create input controls that let the user easily enter both a date and a time, including the year, month, and day as well as the time in hours and minutes.
The control’s UI varies in general from browser to browser. In browsers with no support, these degrade gracefully to simple controls.
The control is intended to represent a local date and time, not necessarily the user’s local date and time. In other words, an implementation should allow any valid combination of year, month, day, hour, and minute—even if such a combination is invalid in the user’s local time zone (such as times within a daylight saving time spring-forward transition gap). Some mobile browsers (particularly on iOS) do not currently implement this correctly.
Because of the limited browser support for datetime-local , and the variations in how the inputs work, it may currently still be best to use a framework or library to present these, or to use a custom input of your own. Another option is to use separate date and time inputs, each of which is more widely supported than datetime-local .
Some browsers may resort to a text-only input element that validates that the results are legitimate date/time values before letting them be delivered to the server, as well, but you shouldn’t rely on this behavior since you can’t easily predict it.
Value | A DOMString representing a date and time (in the local time zone), or empty. |
Events | change and input |
Supported common attributes | autocomplete , list , readonly , and step |
IDL attributes | list , value , valueAsNumber . |
Methods | select() , stepDown() , stepUp() |
Value
A DOMString representing the value of the date entered into the input. The format of the date and time value used by this input type is described in Local date and time strings in Date and time formats used in HTML.
You can set a default value for the input by including a date and time inside the value attribute, like so:
One thing to note is that the displayed date and time formats differ from the actual value ; the displayed date and time are formatted according to the user’s locale as reported by their operating system, whereas the date/time value is always formatted YYYY-MM-DDThh:mm . When the above value submitted to the server, for example, it will look like partydate=2017-06-01T08:30 .
Note: Also bear in mind that if such data is submitted via HTTP GET , the colon character will need to be escaped for inclusion in the URL parameters, e.g. partydate=2017-06-01T08%3A30 . See encodeURI() for one way to do this.
You can also get and set the date value in JavaScript using the HTMLInputElement value property, for example:
There are several methods provided by JavaScript’s Date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually. For example, the Date.toISOString() method can be used for this purpose.
Additional attributes
In addition to the attributes common to all elements, datetime-local inputs offer the following attributes.
The latest date and time to accept. If the value entered into the element is later than this timestamp, the element fails constraint validation. If the value of the max attribute isn’t a valid string which follows the format YYYY-MM-DDThh:mm , then the element has no maximum value.
This value must specify a date string later than or equal to the one specified by the min attribute.
The earliest date and time to accept; timestamps earlier than this will cause the element to fail constraint validation. If the value of the min attribute isn’t a valid string which follows the format YYYY-MM-DDThh:mm , then the element has no minimum value.
This value must specify a date string earlier than or equal to the one specified by the max attribute.
The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any , which is described below. Only values which are equal to the basis for stepping ( min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max ).
Note: When the data entered by the user doesn’t adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.
For datetime-local inputs, the value of step is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of step is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds).
At this time, it’s unclear what a value of any means for step when used with datetime-local inputs. This will be updated as soon as that information is determined.
Using datetime-local inputs
Date/time inputs sound convenient at first glance; they provide an easy UI for choosing dates and times, and they normalize the data format sent to the server, regardless of the user’s locale. However, there are issues with because of the limited browser support.
We’ll look at basic and more complex uses of , then offer advice on mitigating the browser support issue later on (see Handling browser support).
Basic uses of datetime-local
The simplest use of involves a basic and element combination, as seen below:
Setting maximum and minimum dates and times
You can use the min and max attributes to restrict the dates/times that can be chosen by the user. In the following example we are setting a minimum datetime of 2017-06-01T08:30 and a maximum datetime of 2017-06-30T16:30 :
The result here is that:
- Only days in June 2017 can be selected — only the «days» part of the date value will be editable, and dates outside June can’t be scrolled to in the datepicker widget.
- Depending on what browser you are using, you might find that times outside the specified values might not be selectable in the time picker (e.g. Edge), or invalid (see Validation) but still available (e.g. Chrome).
Note: You should be able to use the step attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing.
Controlling input size
doesn’t support form control sizing attributes such as size . You’ll have to resort to CSS for customizing the sizes of these elements.
Setting timezones
One thing the datetime-local input type doesn’t provide is a way to set the time zone and/or locale of the date/time control. 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 time zone along with a date/time input, you could have a element to enable the user to set the right time zone by choosing a particular location from among a set of locations:
In either case, the date/time and time zone 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.
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/time — which is helpful — but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of April).
You can use min and max to restrict the available dates (see Setting maximum and minimum dates), and you can use the required attribute to make filling in the date/time 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 date/time values, 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 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.
Warning: 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 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, 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.
The second problem is the most serious; as we mentioned earlier, with a datetime-local input, the actual value is always normalized to the format YYYY-MM-DDThh:mm . With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates and times, for example:
- DDMMYYYY
- DD/MM/YYYY
- MM/DD/YYYY
- DD-MM-YYYY
- MM-DD-YYYY
- MM-DD-YYYY hh:mm (12 hour clock)
- MM-DD-YYYY HH:mm (24 hour clock)
- etc.
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:
If you try submitting it, you’ll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn’t match the pattern nnnn-nn-nnTnn:nn , where n is a number from 0 to 9. Of course, this doesn’t stop people from entering invalid dates, or incorrectly formatted dates and times.
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.
The Y2K38 Problem (often server-side)
JavaScript uses double precision floating points to store dates, as with all numbers, meaning that JavaScript code will not suffer from the Y2K38 problem unless integer coercion/bit-hacks are used because all JavaScript bit operators use 32-bit signed 2s-complement integers.
The problem is with the server side of things: storage of dates greater than 2^31 — 1. To fix this problem, you must store all dates using either unsigned 32-bit integers, signed 64-bit integers, or double-precision floating points on the server. If your server is written in PHP, the fix may be as simple as upgrading to PHP 8 or 7, and upgrading your hardware to x86_64 or IA64. If you are stuck with other hardware, you can try to emulate 64-bit hardware inside a 32-bit virtual machine, but most VMs don’t support this kind of virtualization, since stability may suffer, and performance will definitely suffer greatly.
The Y10k Problem (often client-side)
In many servers, dates are stored as numbers instead of as strings—numbers of a fixed size and agnostic of format (aside from endianness). After the year 10,000, those numbers will just be a little bit bigger than before, so many servers will not see issues with forms submitted after the year 10,000.
The problem is with the client side of things: parsing of dates with more than 4 digits in the year.
It’s that simple. Just prepare your code for any number of digits. Do not only prepare for 5 digits. Here is JavaScript code for programmatically setting the value:
Why worry about the Y10K problem if it is going to happen many centuries after your death? Exactly because you will already be dead, so the companies using your software will be stuck using your software without any other coder who knows the system well enough to come in and fix it.
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 hard-coded (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 minutes, as there are so many of them!
The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports , we create a new element, try setting its type to datetime-local , then immediately check what its type is set to. Browsers that don’t support datetime-local return text , since that’s what datetime-local falls back to. If is not supported, we hide the native picker and show the fallback picker UI ( ) instead.
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.
Источник