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
echo date ( «l dS of F Y h:i:s A» );

Пример 2. Экранирование символов в функции date()

// вывод: Wednesday the 15th
echo date ( «l \\t\h\e jS» );
?>

Пример 4. Форматирование с использованием date()

// Предположим, что текущая дата March 10th, 2001, 5:16:18 pm

$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 z ‘ ); // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$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 15:16:08 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:17 m is month
$today = date ( «H:i:s» ); // 17:16:17
?>

Источник

PHP get start and end date of a week by weeknumber

I’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.

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

15 Answers 15

A 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.

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

Slightly neater solution, using the «[year]W[week][day]» strtotime format:

shortest way to do it:

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

You can get the specific day of week from date as bellow that I get the first and last day

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

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

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

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 — Форматирует вывод системной даты/времени

Описание

Список параметров

Возвращаемые значения

Ошибки

Список изменений

ВерсияОписание
8.0.0timestamp теперь допускает значение 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:

Источник

Get week number (in the year) from a date PHP

I 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?

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

17 Answers 17

Today, using PHP’s DateTime objects is better:

Hence, your order is wrong.

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

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.

php date week number. Смотреть фото php date week number. Смотреть картинку php date week number. Картинка про php date week number. Фото php date week number

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( ) Считывает информацию о дате и времени. Возвращает ассоциативный массив, содержащий информацию по заданному или по текущему (по умолчанию) времени. Массив содержит следующие элементы:

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 = 25
minutes = 41
hours = 2
mday = 18
wday = 6
mon = 9
year = 2021
yday = 260
weekday = Saturday
month = September
0 = 1631922085
Сегодня: 18.9.2021

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
Сегодня Saturday 18 September 2021 02:41:25
MSK

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *