php date week number
Php date week number
Описание string date ( string format [, int timestamp] )
Замечание: Для большинства систем допустимыми являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Эти даты соответствуют минимальному и максимальному значению 32-битового целого со знаком). Для Windows допустимы даты с 01-01-1970 по 19-01-2038.
Таблица 1. В параметре format распознаются следующие символы
Пример 1. Примеры использования функции date()
// вывод дня недели, например Wednesday echo date ( «l» ); // вывод даты в формате: Wednesday 15th of January 2003 05:51:38 AM Пример 2. Экранирование символов в функции date()
Пример 4. Форматирование с использованием date()
PHP get start and end date of a week by weeknumberI’ve seen some variants on this question but I believe this one hasn’t been answered yet. I need to get the starting date and ending date of a week, chosen by year and week number (not a date) The return value will be something like an array in which the first entry is the week starting date and the second being the ending date. OPTIONAL: while we are at it, the date format needs to be Y-n-j (normal date format, no leading zeros. I’ve tried editing existing functions that almost did what I wanted but I had no luck so far. Please help me out, thanks in advance. 15 Answers 15A shorter version (works in >= php5.3): Many years ago, I found this function: We can achieve this easily without the need for extra computations apart from those inherent to the DateTime class. Slightly neater solution, using the «[year]W[week][day]» strtotime format: shortest way to do it: You can get the specific day of week from date as bellow that I get the first and last day The calculation of Roham Rafii is wrong. Here is a short solution: if you want the last day of the week number, you can add up 6 * 24 * 3600 This is an old question, but many of the answers posted above appear to be incorrect. I came up with my own solution: First we need a day from that week so by knowing the week number and knowing that a week has seven days we are going to do so the this way pickAday will be a day in our desired week. Now because we know the year we can check which day is that. things are simple if we only need dates newer than unix timestamp We will get the unix timestamp for the first day of the year and add to that 24*3600*$pickADay and all is simple from here because we have it’s timestamp we can know what day of the week it is and calculate the head and tail of that week accordingly. Php date week number(PHP 4, PHP 5, PHP 7, PHP 8) date — Форматирует вывод системной даты/времени ОписаниеСписок параметровВозвращаемые значенияОшибкиСписок изменений
ПримерыПример #1 Примеры использования функции date() // установка часового пояса по умолчанию. // выведет примерно следующее: Monday // выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM /* пример использования константы в качестве форматирующего параметра */ Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно. Пример #2 Экранирование символов в функции date() Пример #3 Пример совместного использования функций date() и mktime() Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время. Пример #4 Форматирование с использованием date() // Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера, $today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm ПримечанияСмотрите такжеUser Contributed Notes 20 notesThings to be aware of when using week numbers with years. Conclusion: 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) 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 (); 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 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 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» ); // Add as many holidays as desired. ?> 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: Get week number (in the year) from a date PHPI want to take a date and work out its week number. So far, I have the following. It is returning 24 when it should be 42. Is it wrong and a coincidence that the digits are reversed? Or am I nearly there? 17 Answers 17Today, using PHP’s DateTime objects is better: Hence, your order is wrong. This get today date then tell the week number for the week Just as a suggestion: Might be a little simpler than all that lot. Other things you could do: I have tried to solve this question for years now, I thought I found a shorter solution but had to come back again to the long story. This function gives back the right ISO week notation: I found out that my short solution missed the 2018-12-31 as it gave back 1801 instead of 1901. So I had to put in this long version which is correct. To get the week number for a date in North America I do like this: The most of the above given examples create a problem when a year has 53 weeks (like 2020). So every fourth year you will experience a week difference. This code does not: How about using the IntlGregorianCalendar class? Requirements: Before you start to use IntlGregorianCalendar make sure that libicu or pecl/intl is installed on the Server. So run on the CLI: Дата и время в PHPВ распределенных системах, таких, как Интернет, время играет особую роль. Из-за незначительного расхождения системных часов игрок на рынке Forex может потерять десятки тысяч долларов в течение нескольких минут; система деловой разведки ошибется в составлении прогноза; серверы NNTP в процессе синхронизации потеряют важную информацию, нужную пользователю и т.д. PHP-функции для работы с датой и временемPHP содержит множество функций для работы с датой и временем. Наиболее употребимыми являются: time() Возвращает текущее абсолютное время. Это число равно количеству секунд, которое прошло с полуночи 1 января 1970 года (с начала эпохи UNIX). getdate( ) Считывает информацию о дате и времени. Возвращает ассоциативный массив, содержащий информацию по заданному или по текущему (по умолчанию) времени. Массив содержит следующие элементы:
Пример 1РЕЗУЛЬТАТ ПРИМЕРА 1: seconds = 25 date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды: Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки. Пример 2РЕЗУЛЬТАТ ПРИМЕРА 2: Сегодня 18.09.21 02:41 часы Пример 3РЕЗУЛЬТАТ ПРИМЕРА 3: 22 January 1971, at 1.30 pm, Friday Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970. Пример 4РЕЗУЛЬТАТ ПРИМЕРА 4: Saturday 18 September 2021 02:41
|