php date current date time
PHP Date and Time
The PHP date() function is used to format a date and/or a time.
The PHP Date() Function
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
Parameter | Description |
---|---|
format | Required. Specifies the format of the timestamp |
timestamp | Optional. Specifies a timestamp. Default is the current date and time |
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
Other characters, like»/», «.», or «-» can also be inserted between the characters to add additional formatting.
The example below formats today’s date in three different ways:
Example
Use the date() function to automatically update the copyright year on your website:
Example
Get a Time
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
Example
Note that the PHP date() function will return the current date/time of the server!
Get Your Time Zone
If the time you got back from the code is not correct, it’s probably because your server is in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set the timezone you want to use.
The example below sets the timezone to «America/New_York», then outputs the current time in the specified format:
Example
Create a Date With mktime()
The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above).
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
Syntax
The example below creates a date and time with the date() function from a number of parameters in the mktime() function:
Example
Create a Date From a String With strtotime()
The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Syntax
The example below creates a date and time from the strtotime() function:
Example
PHP is quite clever about converting a string to a date, so you can put in various values:
Example
However, strtotime() is not perfect, so remember to check the strings you put in there.
More Date Examples
The example below outputs the dates for the next six Saturdays:
Example
The example below outputs the number of days until 4th of July:
Example
Complete PHP Date Reference
For a complete reference of all date functions, go to our complete PHP Date Reference.
The reference contains a brief description, and examples of use, for each function!
Дата и время в 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 = 59
minutes = 31
hours = 2
mday = 18
wday = 6
mon = 9
year = 2021
yday = 260
weekday = Saturday
month = September
0 = 1631921519
Сегодня: 18.9.2021
date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды:
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.
Пример 2
РЕЗУЛЬТАТ ПРИМЕРА 2:
Сегодня 18.09.21 02:31
часы
минуты
секунды
месяц
день месяца
год
Пример 3
РЕЗУЛЬТАТ ПРИМЕРА 3:
22 January 1971, at 1.30 pm, Friday
Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.
Пример 4
РЕЗУЛЬТАТ ПРИМЕРА 4:
Saturday 18 September 2021 02:31
Сегодня Saturday 18 September 2021 02:31:59
MSK
Php date current date time
(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:
Класс DateTime
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Введение
Обзор классов
Список изменений
Содержание
User Contributed Notes 26 notes
Set Timezone and formatting.
= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the ‘u’ format string.
// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );
There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.
/**
On my local machine this results in:
Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/
?>
Our solution was to create the following constant on our DateHelper object.
class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>
Small but powerful extension to DateTime
class Blar_DateTime extends DateTime <
= new Blar_DateTime ( ‘1879-03-14’ );
Albert Einstein would now be 130 years old.
Albert Einstein would now be 130 Years, 10 Months, 10 Days old.
Albert Einstein was on 2010-10-10 131 years old.
Example displaying each time format:
$dateTime = new DateTime();
The above example will output:
At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.
This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:
if you’d like to print all the built-in formats,
This might be unexpected behavior:
#or use the interval
#$date1->add(new DateInterval(«P1M»));
#will produce 2017-10-1
#not 2017-09-30
A good way I did to work with millisecond is transforming the time in milliseconds.
function timeToMilliseconds($time) <
$dateTime = new DateTime($time);
If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:
$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));
will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)
To get this done, you will need to set the timezone separately:
$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);
This will create a DateTime object set to «2010-07-05 08:00:00+0200»
It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.
For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:
please note that using
setTimezone
setTimestamp
setDate
setTime
etc..
$original = new DateTime(«now»);
so a datetime object is mutable
(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)
Create function to convert GregorianDate to JulianDayCount
Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.
Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.
It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:
Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:
$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)
Be aware of this behaviour:
In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.
Here is easiest way to find the days difference between two dates:
If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:
If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <
<>
$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 09|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 05|[12]8|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 03|14|22)» ;
$regexpArray [ ‘i’ ] = «(?P54)» ;
$regexpArray [ ‘s’ ] = «(?P25)» ;
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 |
Ниже представлены некоторые примеры получения фактической информации о дате и времени: