Datetime now format php

date_format

The format of the outputted date string . See the formatting options below. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string ‘D, d M Y H:i:s’ .

The following characters are recognized in the format parameter string

format character Description Example returned values
Day
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase ‘L’) A full textual representation of the day of the week Sunday through Saturday
N ISO 8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st , nd , rd or th . Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week
W ISO 8601 week number of year, weeks starting on Monday Example: 42 (the 42nd week in the year)
Month
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year
L Whether it’s a leap year 1 if it is a leap year, 0 otherwise.
o ISO 8601 week-numbering year. This has the same value as Y , except that if the ISO week number ( W ) belongs to the previous or next year, that year is used instead. Examples: 1999 or 2003
X An expanded full numeric representation of a year, at least 4 digits, with — for years BCE, and + for years CE. Examples: -0055 , +0787 , +1999 , +10191
x An expanded full numeric representation if requried, or a standard full numeral representation if possible (like Y ). At least four digits. Years BCE are prefixed with a — . Years beyond (and including) 10000 are prefixed by a + . Examples: -0055 , 0787 , 1999 , +10191
Y A full numeric representation of a year, at least 4 digits, with — for years BCE. Examples: -0055 , 0787 , 1999 , 2003 , 10191
y A two digit representation of a year Examples: 99 or 03
Time
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds with leading zeros 00 through 59
u Microseconds. Note that date() will always generate 000000 since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. Example: 654321
v Milliseconds. Same note applies as for u . Example: 654
Timezone
e Timezone identifier Examples: UTC , GMT , Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) without colon between hours and minutes Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: +02:00
p The same as P , but returns Z instead of +00:00 (available as of PHP 8.0.0) Examples: Z or +02:00
T Timezone abbreviation, if known; otherwise the GMT offset. Examples: EST , MDT , +05
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
Full Date/Time
c ISO 8601 date 2004-02-12T15:19:21+00:00
r » RFC 2822/» RFC 5322 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()
Читайте также:  Html forms action php

Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate() .

Note:

Since this function only accepts int timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create() .

Return Values

Returns the formatted date string on success.

Источник

date

Возвращает строку, отформатированную в соответствии с указанным в параметре format шаблоном. Используется метка времени, заданная параметром timestamp (метка времени Unix), или текущее системное время, если параметр timestamp не задан. Таким образом, параметр timestamp является необязательным и по умолчанию равен значению, возвращаемому функцией time() .

Метки времени Unix не обрабатывают часовые пояса. Используйте класс DateTimeImmutable и его метод форматирования DateTimeInterface::format() для форматирования информации о дате/времени с привязкой к часовому поясу.

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

Замечание: Функция date() всегда будет генерировать 000000 в качестве микросекунд, поскольку она принимает параметр int , тогда как DateTime::format() поддерживает микросекунды, если DateTime был создан с микросекундами.

Необязательный параметр timestamp представляет собой метку времени типа int , по умолчанию равную текущему локальному времени, если timestamp не указан или null . Другими словами, значение по умолчанию равно результату функции time() .

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

Возвращает отформатированную строку с датой.

Ошибки

Каждый вызов к функциям даты/времени при неправильных настройках часового пояса сгенерирует ошибку уровня E_WARNING , если часовой пояс некорректный. Смотрите также date_default_timezone_set()

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

Версия Описание
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’ );

// выведет: July 1, 2000 is on a Saturday
echo «July 1, 2000 is on a » . date ( «l» , mktime ( 0 , 0 , 0 , 7 , 1 , 2000 ));

/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );

// выведет примерно следующее: 2000-07-01T00:00:00+00:00
echo date ( DATE_ATOM , mktime ( 0 , 0 , 0 , 7 , 1 , 2000 ));
?>

Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.

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

Для вывода прошедших и будущих дат удобно использовать функции date() и mktime() .

Пример #3 Пример совместного использования функций date() и mktime()

$tomorrow = mktime ( 0 , 0 , 0 , date ( «m» ) , date ( «d» )+ 1 , date ( «Y» ));
$lastmonth = mktime ( 0 , 0 , 0 , date ( «m» )- 1 , date ( «d» ), date ( «Y» ));
$nextyear = mktime ( 0 , 0 , 0 , date ( «m» ), date ( «d» ), date ( «Y» )+ 1 );
?>

Замечание:

Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.

Ещё несколько примеров использования функции date() . Важно отметить, что следует экранировать все символы, которые необходимо оставить без изменений. Это справедливо и для тех символов, которые в текущей версии PHP не распознаются как форматирующие, поскольку это может быть введено в следующих версиях. Для экранировании управляющих последовательностей (например, \n) следует использовать одинарные кавычки.

Пример #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)
?>

Для форматирования дат на других языках вместо функции date() можно использовать метод IntlDateFormatter::format() .

Примечания

Замечание:

Для получения метки времени из строкового представления даты можно воспользоваться функцией strtotime() . Кроме того, некоторые базы данных имеют собственные функции для преобразования внутреннего представления даты в метку времени (например, функция MySQL » UNIX_TIMESTAMP).

Временную метку начала запроса можно получить из поля $_SERVER[‘REQUEST_TIME’] .

Смотрите также

  • DateTimeImmutable::__construct() — Возвращает новый объект DateTimeImmutable
  • DateTimeInterface::format() — Возвращает дату, отформатированную согласно переданному формату
  • gmdate() — Форматирует дату/время по Гринвичу
  • idate() — Преобразует локальное время/дату в целое число
  • getdate() — Возвращает информацию о дате/времени
  • getlastmod() — Получает время последней модификации страницы
  • mktime() — Возвращает метку времени Unix для заданной даты
  • IntlDateFormatter::format() — Форматирует значение даты/времени в виде строки
  • time() — Возвращает текущую метку системного времени Unix
  • Предопределённые константы даты и времени

User Contributed Notes

  • Функции даты и времени
    • checkdate
    • date_​add
    • date_​create_​from_​format
    • date_​create_​immutable_​from_​format
    • date_​create_​immutable
    • date_​create
    • date_​date_​set
    • date_​default_​timezone_​get
    • date_​default_​timezone_​set
    • date_​diff
    • date_​format
    • date_​get_​last_​errors
    • date_​interval_​create_​from_​date_​string
    • date_​interval_​format
    • date_​isodate_​set
    • date_​modify
    • date_​offset_​get
    • date_​parse_​from_​format
    • date_​parse
    • date_​sub
    • date_​sun_​info
    • date_​sunrise
    • date_​sunset
    • date_​time_​set
    • date_​timestamp_​get
    • date_​timestamp_​set
    • date_​timezone_​get
    • date_​timezone_​set
    • date
    • getdate
    • gettimeofday
    • gmdate
    • gmmktime
    • gmstrftime
    • idate
    • localtime
    • microtime
    • mktime
    • strftime
    • strptime
    • strtotime
    • time
    • timezone_​abbreviations_​list
    • timezone_​identifiers_​list
    • timezone_​location_​get
    • timezone_​name_​from_​abbr
    • timezone_​name_​get
    • timezone_​offset_​get
    • timezone_​open
    • timezone_​transitions_​get
    • timezone_​version_​get

    Источник

    How to Get Current Datetime (NOW) with PHP

    You are currently viewing How to Get Current Datetime (NOW) with PHP

    Various date format expressions are available here.

    Example using date

    This expression will return NOW in format Y-m-d H:i:s

    Example using datetime class

    This expression will return NOW in format Y-m-d H:i:s

    A more complete approach

    Above examples will return NOW using your server timezone, as it is defined in php.ini , for example:

    [Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone = Europe/Athens

    But, the best approach is to save dates to UTC. UTC (also called Zulu time) is the standard international time. All time zones are expressed as offsets of UTC. Especially, if your application users are located in different timezones. Using php DateTime class it is easy to compute the time in user timezone from UTC, and you don’t have to worry about for Daylight Savings Time changes.

    Define server timezone and server date format according to your preferences. My preferences are:

    /* server timezone */ define('CONST_SERVER_TIMEZONE', 'UTC'); /* server dateformat */ define('CONST_SERVER_DATEFORMAT', 'YmdHis');

    In this case, you may use the following simple function:

    = 5.2 * * @param $str_user_timezone * @param string $str_server_timezone * @param string $str_server_dateformat * @return string */ function now($str_user_timezone, $str_server_timezone = CONST_SERVER_TIMEZONE, $str_server_dateformat = CONST_SERVER_DATEFORMAT) < // set timezone to user timezone date_default_timezone_set($str_user_timezone); $date = new DateTime('now'); $date->setTimezone(new DateTimeZone($str_server_timezone)); $str_server_now = $date->format($str_server_dateformat); // return timezone to server default date_default_timezone_set($str_server_timezone); return $str_server_now; > ?>

    Entrepreneur | Full-stack developer | Founder of MediSign Ltd. I have over 15 years of professional experience designing and developing web applications. I am also very experienced in managing (web) projects.

    Источник

Оцените статью