input date php format
date — Форматирует вывод системной даты/времени
Описание
Список параметров
Шаблон результирующей строки ( string ) с датой. См. параметры форматирования ниже. Также существует несколько предопределенных констант даты/времени, которые могут быть использованы вместо этих параметров. Например: DATE_RSS заменяет шаблон ‘D, d M Y H:i:s’.
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5.1.0 | Допустимым диапазоном дат для временных меток обычно являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Они соответствуют минимальному и максимальному значению 32-битного целого числа со знаком). Однако для PHP версии ниже 5.1.0 в некоторых операционных системах (например, Windows) этот диапазон был ограничен датами 01-01-1970 до 19-01-2038. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
5.1.0 |
Версия | Описание |
---|---|
8.0.0 | timestamp теперь допускает значение null. |
Примеры
Пример #1 Примеры использования функции date()
// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );
// выведет примерно следующее: Monday
echo date ( «l» );
// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );
/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );
Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.
Пример #2 Экранирование символов в функции date()
Пример #3 Пример совместного использования функций date() и mktime()
Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.
Пример #4 Форматирование с использованием date()
// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)
$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (формат MySQL DATETIME)
?>
Примечания
Смотрите также
User Contributed Notes 20 notes
Things to be aware of when using week numbers with years.
Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.
In order to define leap year you must considre not only that year can be divide by 4!
The correct alghoritm is:
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)
So the code should look like this:
For Microseconds, we can get by following:
echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);
FYI: there’s a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:
echo date ( ‘Y-m-d\TH:i:sO’ );
?>
You can use
echo date ( DateTime :: ISO8601 );
?>
instead, which is much easier to read.
this how you make an HTML5 tag correctly
It’s common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP’s built-in functions. Consider http://php.net/manual/en/function.date.php#108613
date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(. ). Local time. If you want to output as UTC time use:
$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );
For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57
To generate this, escape the ‘T’, as shown below:
If timestamp is a string, date converts it to an integer in a possibly unexpected way:
The example below formats today’s date in three different ways:
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
At least in PHP 5.5.38 date(‘j.n.Y’, 2222222222) gives a result of 2.6.2040.
So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.
Prior to PHP 5.6.23, Relative Formats for the start of the week aligned with PHP’s (0=Sunday,6=Saturday). Since 5.6.23, Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)
This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of ‘w’ or ‘N’ for the Numeric representation of the day of the week:
Prior to PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016
Since PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016
I’ve tested it pretty strenuously but date arithmetic is complicated and there’s always the possibility I missed something, so please feel free to check my math.
The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. «skip all Fridays and Saturdays but include Sundays») or to set up dates that should always be skipped (e.g. «skip July 4th in any year, skip the first Monday in September in any year»). But that’s a project for another time.
$start = strtotime ( «1 January 2010» );
$end = strtotime ( «13 December 2010» );
// Add as many holidays as desired.
$holidays = array();
$holidays [] = «4 July 2010» ; // Falls on a Sunday; doesn’t affect count
$holidays [] = «6 September 2010» ; // Falls on a Monday; reduces count by one
?>
Or, if you just want to know how many work days there are in any given year, here’s a quick function for that one:
In which format should I put the date and time, for use in the HTML5 input element with datetime type?
None of them seem to work.
7 Answers 7
A string representing a global date and time.
Value: A valid date-time as defined in [RFC 3339], with these additional qualifications:
•the literal letters T and Z in the date/time syntax must always be uppercase
•the date-fullyear production is instead defined as four or more digits representing a number greater than 0
Examples:
Update:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
The HTML was a control for entering a date and time (hour, minute, second, and fraction of a second) as well as a timezone. This feature has been removed from WHATWG HTML, and is no longer supported in browsers.
Instead, browsers are implementing (and developers are encouraged to use) the datetime-local input type.
For what it’s worth, with iOS7 dropping support for datetime you need to use datetime-local which doesn’t accept timezone portion (which makes sense).
Doesn’t work (iOS anyway):
PHP for value (windows safe):
This article seems to show the valid types that are acceptable
This one covers using it in the field:
This example of the HTML5 input type «date» combine with the attributes min and max shows how we can restrict the dates a user can input. The attributes min and max are not dependent on each other and can be used independently.
The HTML5 input type «time» allows users to choose a corresponding time that is displayed in a 24hour format. If we did not include the default value of «12:00» the time would set itself to the time of the users local machine.
The HTML5 Input type week will display the numerical version of the week denoted by a «W» along with the corresponding year.
The HTML5 input type month does exactly what you might expect it to do. It displays the month. To be precise it displays the numerical version of the month along with the year.
The HTML5 input type Datetime displays the UTC date and time code. User can change the the time steps forward or backward in one minute increments. If you wish to display the local date and time of the user you will need to use the next example datetime-local
Because datetime steps through one minute at a time, you may want to change the default increment by using the attribute «step». In the following example we will have it increment by two hours by setting the attribute step to 7200 (60seconds X 60 minutes X 2).
PHP | Дата и время
В этом уроке рассмотрм, как на практике использовать функции PHP по получению даты и времени, а также рассмотрим способы вывода и форматирования даты и времени. Функции PHP, обрабатывающие дату и время, позволяют получать дату и время с того сервера, на котором выполняется сценарий. Также эти функции позволяют нам редактировать и форматировать полученные временные значения перед их отображением (выводом) на экран.
Функция PHP date()
Функция date() выводит текущие дату и время в заданном формате. Также функция может конвертировать формат отметки времени (временная метка, метка времени или timestamp) в удобочитаемый формат.
Синтаксис
Параметры функции date():
Примечание: Отметка времени — это последовательность символов, обозначающая дату и / или время, когда произошло определенное событие.
Обязательный параметр format функции date() указывает, как форматировать дату (или время). Формат задается управляющими командами (латиницей), при этом можно вставлять любые разделители между ними (дефисы, двоеточие и так далее).
Ниже представлена таблица с расшифровкой некоторых символов в строке format :
Символ в строке format | Описание | Пример возвращаемого значения |
---|---|---|
День | — | — |
d | День месяца с 2-мя цифрами | от 01 до 31 |
D | День недели в текстовом формате, 3 символа | от Mon до Sun |
z | Порядковый номер дня в году (начиная с 0) | От 0 до 365 |
Месяц | — | — |
F | Полное название месяца, например, January или March | от January до December |
m | Порядковый номер месяца, 2 цифры | от 01 до 12 |
M | Сокращенное название месяца, 3 символа | от Jan до Dec |
Год | — | — |
Y | Порядковый номер года, 4 цифры | Примеры: 1999, 2019 |
y | Порядковый номер года, 2 цифры | Примеры: 99, 19 |
Время | — | — |
a | Ante meridiem (лат. «до полудня») или Post meridiem (лат. «после полудня») в нижнем регистре | am или pm |
A | Ante meridiem или Post meridiem в верхнем регистре | AM или PM |
g | Часы в 12-часовом формате | от 1 до 12 |
G | Часы в 24-часовом формате | от 0 до 23 |
h | Часы в 12-часовом формате | от 01 до 12 |
H | Часы в 24-часовом формате, 2 цифры | от 00 до 23 |
i | Минуты, 2 цифры | от 00 до 59 |
s | Секунды, 2 цифры | от 00 до 59 |
Ниже представлены некоторые примеры получения фактической информации о дате и времени:
Input date php format
elements of type=»date» create input fields that let the user enter a date, either with a textbox that validates the input or a special date picker interface.
The resulting value includes the year, month, and day, but not the time. The time and datetime-local input types support time and date+time input.
Among browsers with custom interfaces for selecting dates are Chrome, Edge, and Opera, whose date control looks like so:
And the Firefox date control looks like this:
Value
A DOMString representing the date entered in the input. The date is formatted according to ISO8601, described in Format of a valid date string in Date and time formats used in HTML.
You can set a default value for the input with a date inside the value attribute, like so:
You can get and set the date value in JavaScript with the HTMLInputElement value and valueAsNumber properties. For example:
Additional attributes
Along with the attributes common to all elements, date inputs have the following attributes:
Attribute | Description |
---|---|
max | The latest acceptable date |
min | The earliest acceptable date |
step | The stepping interval, when clicking up and down spinner buttons and validating the date |
If both the max and min attributes are set, this value must be a date string later than or equal to the one in the min attribute.
If both the max and min attributes are set, this value must be a date string earlier than or equal to the one in the max attribute.
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 date inputs, the value of step is given in days; and is treated as a number of milliseconds equal to 86,400,000 times the step value (the underlying numeric value is in milliseconds). The default value of step is 1, indicating 1 day.
Specifying any as the value for step has the same effect as 1 for date inputs.
Using date inputs
Date inputs sound convenient — they provide an easy interface for choosing dates, and they normalize the data format sent to the server regardless of the user’s locale. However, there are currently issues with because of its limited browser support.
Hopefully, over time browser support will become ubiquitous, and this problem will fade away.
Basic uses of date
Setting maximum and minimum dates
You can use the min and max attributes to restrict the dates that can be chosen by the user. In the following example, we set a minimum date of 2017-04-01 and a maximum date of 2017-04-30 :
The result is that only days in April 2017 can be selected — the month and year parts of the textbox will be uneditable, and dates outside April 2017 can’t be selected in the picker widget.
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. to only make Saturdays selectable). However, this does not seem to be in any implementation at the time of writing.
Controlling input size
Validation
By default, doesn’t validate the entered value beyond its format. The interfaces generally don’t let you enter anything that isn’t a date — which is helpful — but you can leave the field empty or enter an invalid date in browsers where the input falls back to type text (like 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 out of bounds. However, you’ll need to double-check the submitted results to ensure the value is within these dates, if the date picker isn’t fully supported on the user’s device.
You can also use the required attribute to make filling in the date mandatory — an error will be displayed if you try to submit an empty date field. This should work in most browsers, even if they fall back to a text input.
Let’s look at an example of minimum and maximum dates, and also made a 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. We make use of the :valid and :invalid pseudo-elements to add an icon next to the input, based on whether or not the current value is valid. We had to put the icon on a next to the input, not on the input itself, because in Chrome at least the input’s generated content is placed inside the form control, and can’t be styled or shown effectively.
Important: Client-side form validation is no substitute for validating on the server. It’s easy for someone to modify the HTML, or bypass your HTML entirely and submit the data directly to your server. If your server fails to validate the received data, disaster could strike with data that is badly-formatted, too large, of the wrong type, etc.
Handling browser support
As mentioned, the major problem with date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:
Unsupporting browsers gracefully degrade to a text input, but this creates problems in consistency of user interface (the presented controls are different) and data handling.
One way around this is the pattern attribute on your date input. Even though the date picker doesn’t use it, the text input fallback will. For example, try viewing the following in a unsupporting browser:
If you submit it, you’ll see that the browser displays an error and highlights the input as invalid if your entry doesn’t match the pattern ####-##-## (where # is a digit from 0 to 9). Of course, this doesn’t stop people from entering invalid dates, or incorrect formats. So we still have a problem.
At the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a JavaScript library such as jQuery date picker.
Examples
In this example, we create 2 sets of UI elements for choosing dates: a native picker and a set of 3 elements for older browsers that don’t support the native date 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.
- innovert isd mini настройка параметров
- input not support на мониторе как исправить