php последний день текущего месяца
mktime
(PHP 4, PHP 5, PHP 7, PHP 8)
mktime — Возвращает метку времени Unix для заданной даты
Описание
Аргументы могут быть опущены в порядке справа налево. В этом случае их значения по умолчанию равны соответствующим компонентам локальной даты/времени.
Список параметров
Возвращаемые значения
Ошибки
Список изменений
Примеры
Пример #1 Пример использования функции mktime()
// Устанавливаем используемый по умолчанию часовой пояс.
date_default_timezone_set ( ‘UTC’ );
Пример #2 Пример использования mktime()
Функцию mktime() удобно использовать для выполнения арифметических операций с датами, так как она вычисляет верные значения при некорректных аргументах. Например, в следующем примере каждая строка выведет «Jan-01-1998».
Пример #3 Последний день месяца
Смотрите также
User Contributed Notes 27 notes
Do remember that, counter-intuitively enough, the arguments for month and day are inversed (or middle-endian). A common mistake for Europeans seems to be to feed the date arguments in the expected order (big endian or little endian).
Be careful passing zeros into mktime, in most cases a zero will count as the previous unit of time. The documentation explains this yet most of the comments here still use zeroes.
For example, if you pass the year 2013 into mktime, with zeroes for everything else, the outcome is probably not what you are looking for.
Please note, mktime requires an integer value, if you use date(«H»), date(«i»), date(«s») as a value, which is actually have a leading zero, you may get «A non well formed numeric value encountered» notice. so you need some tricks like this
mktime( date(«G»), intval(date(«i»)), intval(date(«s»), date(«n»), date(«j»), date(«Y») )
Since there are no minute & second without leading zero in the date function, we can use the intval() function or you can cast value type like this to force the value type.
I was using the following to get a list of month names.
Pay attention that not all days have the same number of seconds (86400s) if you are using date_default_timezone_set(..) and the used timezone has Daylight Saving Time (DST) e.g. «Europe/Berlin». Under PHP 5.5.16 I get the following results:
You may workaround this by using date_default_timezone_set(‘UTC’) where all days have the same number of seconds.
The following function moves all the parameters in order of most significant (biggest) to least significant (smallest) order.
Year is bigger than month. Month is bigger than day. Day bigger than hours.
Much less confusing than mktime order.
Add (and subtract) unixtime:
Function to generate array of dates between two dates (date range array)
echo » ;
?>
[EDIT BY danbrown AT php DOT net: Contains a bugfix submitted by (carlosbuz2 AT gmail DOT com) on 04-MAR-2011, with the following note: The first date in array is incorrect.]
The maximum possible date accepted by mktime() and gmmktime() is dependent on the current location time zone.
You cannot simply subtract or add month VARs using mktime to obtain previous or next months as suggested in previous user comments (at least not with a DD > 28 anyway).
If the date is 03-31-2007, the following yeilds March as a previous month. Not what you wanted.
If you are just looking to do month and year arithmetic using mktime, you can use general days like 1 or 28 to do stuff like this:
What’s odd is that mktime doesn’t seem to support every possible year number. It’s common sense that 2 digit (shortened) year numbers are interpreted in the range 1970..2069
However, when padded with zeroes, no such transformation should happen (at least that is the behaviour of other date functions). Unfortunately it does (until year 100 *inclusive*):
>*/
if(strlen($value[2])==4)/13/12/2012
//int mktime([hour[minute[second[month[day[year
return mktime(0, 0, 0,$value[1],$value[0],$value[2]);
>else < //2012/12/13
//int mktime([hour[minute[second[month[day[year
return mktime(0, 0, 0,$value[1],$value[2],$value[0]);
>
>
caculate days between two date
There are several warnings here about using mktime() to determine a date difference because of daylight savings time. However, nobody seems to have mentioned the other obvious problem, which is leap years.
Leap years mean that any effort to use mktime() and time() to determine the age (positive or negative) of some timestamp in years will be flawed. There are some years that are 366 days long, therefore you cannot say that there is a set number of seconds per year.
Timestamps are good for determining *real* time, which is not the same thing as *human calendar* time. The Gregorian calendar is only an approximation of real time, which is tweaked with daylight savings time and leap years to make it conform more to humans’ expectations of how time should or ought to work. Timestamps are not tweaked and therefore are the only authoritative way of recording in computers a proper order of succession of events, but they cannot be integrated with a Gregorian system unless you take both leap years and DST into account. Otherwise, you may get the wrong number of years when you are approaching a value of exactly X years.
As for PHP, you could still use timestamps as a way of determining age if you took into account not only DST but also whether or not each year is a leap year and adjusted your calculations accordingly. However, this could become messy and inefficient.
This solution works because it stays within the Gregorian system and doesn’t venture into the world of timestamps.
There is also the issue of leap seconds, but this will only arise if you literally need to get the *exact* age in seconds. In that case, of course, you would also need to verify that your timestamps are exactly correct and are not delayed by script processing time, plus you would need to determine whether your system conforms to UTC, etc. I expect this will hardly be an issue for anybody using PHP, however if you are interested there is an article on this issue on Wikipedia:
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:
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.
For Microseconds, we can get by following:
echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);
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
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.
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:
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’ );
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:
Дата и время в 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 = 45
minutes = 42
hours = 0
mday = 5
wday = 5
mon = 11
year = 2021
yday = 308
weekday = Friday
month = November
0 = 1636062165
Сегодня: 5.11.2021
date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды:
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.
Пример 2
РЕЗУЛЬТАТ ПРИМЕРА 2:
Сегодня 05.11.21 00:42
часы
минуты
секунды
месяц
день месяца
год
Пример 3
РЕЗУЛЬТАТ ПРИМЕРА 3:
22 January 1971, at 1.30 pm, Friday
Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.
Пример 4
РЕЗУЛЬТАТ ПРИМЕРА 4:
Friday 05 November 2021 00:42
Сегодня Friday 05 November 2021 00:42:45
MSK
Как найти последний день месяца с даты?
Как я могу получить последний день месяца в PHP?
Я хочу 2009-11-30; и дано
t возвращает количество дней в месяце заданной даты (см. документы для date ):
Код с использованием strtotime () завершится с ошибкой после 2038 года (как указано в первом ответе в этом потоке) Например, попробуйте использовать следующее:
Он даст ответ как: 1970-01-31
Поэтому вместо strtotime следует использовать функцию DateTime. Следующий код будет работать без проблемы года 2038:
Это должно работать:
Попробуйте это, если вы используете PHP 5.3+,
Чтобы найти следующий последний месяц, измените следующим образом:
Если вы используете расширение API Carbon для PHP DateTime, вы можете получить последний день месяца:
Что случилось с вами, ребята? Наиболее элегантным является использование DateTime
Вы можете найти последний день месяца несколькими способами. Но просто вы можете сделать это с помощью функции PHP strtotime () и date (). Я предполагаю, что ваш последний код будет выглядеть примерно так:
Но если вы используете PHP> = 5.2, я настоятельно рекомендую вам использовать новый объект DateTime. Например, как показано ниже:
Кроме того, вы можете решить это, используя свою собственную функцию, как показано ниже:
Вы также можете использовать его с datetime
Вот полная функция:
Это будет выводиться следующим образом:
Есть способы получить последний день месяца.
Использование Zend_Date довольно просто:
Расширение API Carbon для PHP DateTime
Я опаздываю, но есть несколько простых способов сделать это, как уже упоминалось:
Использование mktime () – это мой полный контроль над всеми аспектами времени … IE
Установка дня на 0 и перемещение вашего месяца до 1 даст вам последний день предыдущего месяца. 0, а отрицательные числа имеют аналогичный аффект в разных аргументах. PHP: mktime – Руководство
Как некоторые из них сказали, что strtotime – это не самый надежный способ пойти, и мало, если никто не будет столь же легко универсальным.
Другой способ использования mktime и not date (‘t’):
Таким образом, он рассчитывает либо, если он равен 31,30 или 29
Это гораздо более элегантный способ получить конец месяца:
Вы можете использовать функцию « t » в функции даты, чтобы получить количество дней в определенном месяце.
Код будет примерно таким:
Код сам объясняется. Поэтому надеюсь, что это поможет.
В PHP есть простой способ получить первую и последнюю дату месяца?
Мне нужно получить первый и последний день месяца в формате гггг-ММ-ДД дали только месяц и год. Есть хороший, простой способ сделать это?
11 ответов
посмотреть date () в документации PHP.
первый день всегда гггг-мм-01, не так ли? Пример: date(«Y-M-d», mktime(0, 0, 0, 8, 1, 2008))
последний день накануне первого дня следующего месяца:
в первый день месяца всегда равен 1. Так оно и станет
последний день можно рассчитать как:
хорошо, сначала очень легко.
последние немного сложнее, но не намного.
Если я правильно помню свою дату PHP.
* * edit-Gah! Его били около миллиона раз.
последний день должен был
кстати @ZombieSheep решение
не работает, он должен быть!—3—>
конечно, принятое решение @ Michał Słaby является самым простым.
просто чтобы убедиться, что я не пропустил свободные концы:
самый простой способ сделать это с PHP
или на прошлой неделе
попробуйте это, чтобы получить количество дней в месяце:
пример; я хочу получить первый и последний день текущего месяца.
при запуске этого, например, на дату 2015-01-09, первое и последнее значения будут последовательно;
С здесь (получить следующий месяц в последний день) это помечено как Дублированное, поэтому я не могу добавить комментарий там, но люди могут получить плохие ответы оттуда.
правильным для последнего дня следующего месяца:
правильным для первого дня следующего месяца:
такой код будет предоставлять март с января, так что это не то, что можно было ожидать.
echo ((new DateTime())->modify(‘+1 month’)->format(‘Y-m-t’));