php get date current date
Php get date current date
(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:
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!
How do I use PHP to get the current year?
I want to put a copyright notice in the footer of a web site, but I think it’s incredibly tacky for the year to be outdated.
How would I make the year update automatically with PHP 4 or PHP 5?
31 Answers 31
You can use either date or strftime. In this case I’d say it doesn’t matter as a year is a year, no matter what (unless there’s a locale that formats the year differently?)
On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:
To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().
From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that’s not an issue, pick the one you like best.
My super lazy version of showing a copyright line, that automatically stays updated:
This year (2008), it will say:
Next year, it will say:
and forever stay updated with the current year.
Or (PHP 5.3.0+) a compact way to do it using an anonymous function so you don’t have variables leaking out and don’t repeat code/constants:
With PHP heading in a more object-oriented direction, I’m surprised nobody here has referenced the built-in DateTime class:
or one-liner with class member access on instantiation (php>=5.4):
I love strftime. It’s a great function for grabbing/recombining chunks of dates/times.
Plus it respects locale settings which the date function doesn’t do.
This one gives you the local time:
And this one UTC:
below is a bit of explanation of what it does:
Y will gives you four digit (e.g. 1990) and y for two digit (e.g. 90)
For 4 digit representation:
2 digit representation:
echo date(‘Y’) gives you current year, and this will update automatically since date() give us the current date.
It takes the current date and then you provide a format to it
and the format is just going to be Y. Capital Y is going to be a four digit year.
This code should do
And ‘echo’ this value.
If your server supports Short Tags, or you use PHP 5.4, you can use:
BTW. there are a few proper ways how to display site copyright. Some people have tendency to make things redundant i.e.: Copyright © have both the same meaning. The important copyright parts are:
Or you can use it with one line
If you wanna increase or decrease the year another method; add modify line like below.
use a PHP date() function.
and the format is just going to be Y. Capital Y is going to be a four digit year.
Get full Year used:
Or get only two digit of year used like this:
My way to show the copyright, That keeps on updating automatically
It will output the results as
best shortcode for this section:
You can use this in footer sections to get dynamic copyright year
in my case the copyright notice in the footer of a wordpress web site needed updating.
thought simple, but involved a step or more thann anticipated.
Open footer.php in your theme’s folder.
Locate copyright text, expected this to be all hard coded but found:
Now we know the year is written somewhere in WordPress admin so locate that to delete the year written text. In WP-Admin, go to Options on the left main admin menu:
Then on next page go to the tab Disclaimers :
and near the top you will find Copyright year:
DELETE the © symbol + year + the empty space following the year, then save your page with Update button at top-right of page.
With text version of year now delete, we can go and add our year that updates automatically with PHP. Go back to chunk of code in STEP 2 found in footer.php and update that to this:
Done! Just need to test to ensure changes have taken effect as expected.
this might not be the same case for many, however we’ve come across this pattern among quite a number of our client sites and thought it would be best to document here.
Дата и время в 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 = 2
minutes = 15
hours = 5
mday = 18
wday = 6
mon = 9
year = 2021
yday = 260
weekday = Saturday
month = September
0 = 1631931302
Сегодня: 18.9.2021
date() Форматирование даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. Строка формата может содержать следующие коды:
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.
Пример 2
РЕЗУЛЬТАТ ПРИМЕРА 2:
Сегодня 18.09.21 05:15
часы
минуты
секунды
месяц
день месяца
год
Пример 3
РЕЗУЛЬТАТ ПРИМЕРА 3:
22 January 1971, at 1.30 pm, Friday
Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.
Пример 4
РЕЗУЛЬТАТ ПРИМЕРА 4:
Saturday 18 September 2021 05:15
Сегодня Saturday 18 September 2021 05:15:02
MSK
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 |
Ниже представлены некоторые примеры получения фактической информации о дате и времени: