php текст в дату
Дата и время в PHP
В распределенных системах, таких, как Интернет, время играет особую роль. Из-за незначительного расхождения системных часов игрок на рынке Forex может потерять десятки тысяч долларов в течение нескольких минут; система деловой разведки ошибется в составлении прогноза; серверы NNTP в процессе синхронизации потеряют важную информацию, нужную пользователю и т.д.
PHP-функции для работы с датой и временем
PHP содержит множество функций для работы с датой и временем. Наиболее употребимыми являются:
time() Возвращает текущее абсолютное время. Это число равно количеству секунд, которое прошло с полуночи 1 января 1970 года (с начала эпохи UNIX). getdate( ) Считывает информацию о дате и времени. Возвращает ассоциативный массив, содержащий информацию по заданному или по текущему (по умолчанию) времени. Массив содержит следующие элементы:
seconds | Секунды (0-59) |
minutes | Минуты (0-59) |
hours | Часы (0-23) |
mday | День месяца (1-31) |
wday | День недели (0-6), начиная с воскресенья |
mon | Месяц (1-12) |
year | Год |
yday | День года (0-365) |
weekday | Название дня недели (например, Friday) |
month | Название месяца (например, January) |
0 | Абсолютное время |
Пример 1
РЕЗУЛЬТАТ ПРИМЕРА 1:
seconds = 49
minutes = 35
hours = 8
mday = 20
wday = 1
mon = 9
year = 2021
yday = 262
weekday = Monday
month = September
0 = 1632116149
Сегодня: 20.9.2021
date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды:
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.
Пример 2
РЕЗУЛЬТАТ ПРИМЕРА 2:
Сегодня 20.09.21 08:35
часы
минуты
секунды
месяц
день месяца
год
Пример 3
РЕЗУЛЬТАТ ПРИМЕРА 3:
22 January 1971, at 1.30 pm, Friday
Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.
Пример 4
РЕЗУЛЬТАТ ПРИМЕРА 4:
Monday 20 September 2021 08:35
Сегодня Monday 20 September 2021 08:35:49
MSK
PHP | Преобразование строки в Date и DateTime
Преобразование строки в Date и DateTime использует несколько функций / методов, таких как strtotime (), getDate (). Посмотрим, что делают эти функции.
strtotime () — в основном это функция, которая возвращает количество секунд, прошедших с 1 января 1970 года, точно так же, как отметка времени машины linux. Возвращает количество секунд, переданных в соответствии с параметром, переданным функции.
Синтаксис
параметр
Возвращаемый тип Возвращает количество секунд, прошедших с 1 января 1970 года.
getDate () Эта функция возвращает информацию о дате / времени переданного параметра (дата / время);
Синтаксис
Параметр Параметр является необязательным, поскольку он принимает текущее местное время в качестве параметра по умолчанию.
Возвращаемый тип Возвращает информацию о дате, дне, году, месяце и т. Д. В массиве.
Код для преобразования строки в дату
$time_input = strtotime ( «2011/05/21» );
Код для преобразования строки в dateTime
$input = ’06/10/2011 19:00:02′ ;
Примечание1 Мы можем использовать «D» вместо «d» для получения дня в выходных данных
$input = ’05/10/2011 15:00:02′ ;
Примечание 2 Мы можем использовать «H» вместо «h» для получения времени в 24-часовом формате на выходе
$input = ’05/10/2011 15:00:02′ ;
Точно так же, «i» и «s» также можно изменить на прописные, чтобы найти разные выходные данные, это возможно, но не очень полезно.
Php текст в дату
(PHP 4, PHP 5, PHP 7, PHP 8)
date — Форматирует вывод системной даты/времени
Описание
Список параметров
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
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:
strtotime
(PHP 4, PHP 5, PHP 7, PHP 8)
strtotime — Преобразует текстовое представление даты на английском языке в метку времени Unix
Описание
Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания часового пояса различными способами.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.
Временная метка, используемая в качестве базы для вычисления относительных дат.
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
8.0.0 | baseTimestamp теперь допускает значение null. |
Примеры
Пример #1 Пример использования функции strtotime()
Пример #2 Проверка ошибок
Примечания
Корректным диапазоном временных меток обычно являются даты с 13 декабря 1901 20:45:54 UTC по 19 января 2038 03:14:07 UTC. (Эти даты соответствуют минимальному и максимальному значению 32-битового знакового целого).
В 64-битных версиях PHP корректный диапазон временных меток фактически бесконечен, так как 64 битов хватит для представления приблизительно 293 миллиарда лет в обоих направлениях.
Чтобы избежать потенциальной неоднозначности, рекомендуется использовать даты в формате стандарта ISO 8601 ( YYYY-MM-DD ), либо пользоваться функцией DateTime::createFromFormat() там, где это возможно.
Смотрите также
User Contributed Notes 42 notes
I’ve had a little trouble with this function in the past because (as some people have pointed out) you can’t really set a locale for strtotime. If you’re American, you see 11/12/10 and think «12 November, 2010». If you’re Australian (or European), you think it’s 11 December, 2010. If you’re a sysadmin who reads in ISO, it looks like 10th December 2011.
The best way to compensate for this is by modifying your joining characters. Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.
The «+1 month» issue with strtotime
===================================
As noted in several blogs, strtotime() solves the «+1 month» («next month») issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.
A strtotime também funciona quando concatenamos strings,
UK dates (eg. 27/05/1990) won’t work with strotime, even with timezone properly set.
[red., derick]: What you instead should do is:
WARNING when using «next month», «last month», «+1 month», «-1 month» or any combination of +/-X months. It will give non-intuitive results on Jan 30th and 31st.
The way to get what people would generally be looking for when they say «next month» even on Jan 30 and Jan 31 is to use «first day of next month»:
strtotime() also returns time by year and weeknumber. (I use PHP 5.2.8, PHP 4 does not support it.) Queries can be in two forms:
— «yyyyWww», where yyyy is 4-digit year, W is literal and ww is 2-digit weeknumber. Returns timestamp for first day of week (for me Monday)
— «yyyy-Www-d», where yyyy is 4-digit year, W is literal, ww is 2-digit weeknumber and dd is day of week (1 for Monday, 7 for Sunday)
// Get timestamp of 32nd week in 2009.
strtotime ( ‘2009W32’ ); // returns timestamp for Mon, 03 Aug 2009 00:00:00
// Weeknumbers strtotime ( ‘2009W01’ ); // returns timestamp for Mon, 29 Dec 2008 00:00:00
// strtotime(‘2009W1’); // error! returns false
// See timestamp for Tuesday in 5th week of 2008
strtotime ( ‘2008-W05-2’ ); // returns timestamp for Tue, 29 Jan 2008 00:00:00
?>
Weeknumbers are (probably) computed according to ISO-8601 specification, so doing date(‘W’) on given timestamps should return passed weeknumber.
I tried using sams most popular example but got incorrect results.
Then I read the notes which said:
if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. ***If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.***
I run a theatre’s website. Obviously, I need to ensure shows that have already happened do not appear on web pages, so I use something on the lines of:
So strtotime($end_date) will always return the timestamp at 00:00 that day. If I instead used:
You are not restricted to the same date ranges when running PHP on a 64-bit machine. This is because you are using 64-bit integers instead of 32-bit integers (at least if your OS is smart enough to use 64-bit integers in a 64-bit OS)
The following code will produce difference output in 32 and 64 bit environments.
32-bit PHP: bool(false)
64-bit PHP: int(-30607689600)
This is true for php 5.2.* and 5.3
Also, note that the anything about the year 10000 is not supported. It appears to use only the last digit in the year field. As such, the year 10000 is interpretted as the year 2000; 10086 as 2006, 13867 as 2007, etc
For negative UNIX timestamps, strtotime seems to return the literal you passed in, or it may try to deduct the number of seconds from today’s date.
To work around this behaviour, it appears that the same behaviour as described in the DateTime classes applies:
Specifically this line here (in the EN manual):
Therefore strtotime(‘@-1000’) returns 1000 seconds before the epoch.
It took me a while to notice that strtotime starts searching from just after midnight of the first day of the month. So, if the month starts on the day you search for, the first day of the search is actually the next occurrence of the day.
In my case, when I look for first Tuesday of the current month, I need to include a check to see if the month starts on a Tuesday.
If you want to confront a date stored into mysql as a date field (not a datetime) and a date specified by a literal string, be sure to add «midnight» to the literal string, otherwise they won’t match:
//I.E.: today is 17/02/2011
echo strtotime ( ‘2011-01-01’ ); //1293836400
echo strtotime ( ‘first day of last month’ ); //1293888128 Note: it’s different from the previous one, since it computes also the seconds passed from midnight. So this one is always greater than simple ‘2011-01-01’
echo strtotime ( ‘midnight first day of last monty’ ); //1293836400 Note: it’s the same as ‘2011-01-01’
Apache claims this to be a ‘standard english format’ time. strtotime() feels otherwise.
I came up with this function to assist in parsing this peculiar format.
strtotime is awesome for converting dates.
in this example i will make an RSS date, an
ATOM date, then convert them to a human
readable m/d/Y dates.
[red.: This is a bug, and should be fixed. I have file an issue]
This comment apply to PHP5+
We can now do thing like this with strtotime:
= strtotime ( ‘Monday this week’ );
?>
However this works based on a week starting Sunday. I do not know if we can tweak this PHP behavior, anyone know?
strtotime() will convert a string WITHOUT a timezone indication as if the string is a time in the default timezone ( date_default_timezone_set() ). So converting a UTC time like ‘2018-12-06T09:04:55’ with strtotime() actually yields a wrong result. In this case use:
Adding a note to an already long page:
Try to be as specific as you can with the string you pass in. For example
Assuming today is July 31, the timestamp returned by strtotime(‘February’) will ultimately be seen as February 31 (non-existant obviously), which then is interpreted as March 3, thus giving a month name of March.
Interestingly, adding the year or the day will give you back the expected month.
strtotime() produces different output on 32 and 64 bit systems running PHP 5.3.3 (as mentioned previously). This affects the «zero date» («0000-00-00 00:00:00») as well as dates outside the traditional 32 date range.
In modern 64-bit systems (tested on mac) the old 1970 to 2038 date range limitations are gone.
strtotime(«0001-10-30») gives int(-62109540728)
strtotime(«6788-10-30») gives int(152067506400)
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 |
Ниже представлены некоторые примеры получения фактической информации о дате и времени: