php date create from format

date_create_from_format

Описание

Создает и возвращает экземпляр класса DateTime, соответствующий заданному формату.

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

Список возможных символов для составления строки format

Символ в строке formatОписаниеВозможные значения
День
d и jДень месяца, 2 цифры с нулем в начале или без негоОт 01 до 31 либо от 1 до 31
D и lТекстовое представление дня месяцаОт Mon до Sun либо от Sunday до Saturday
SСуффикс для числа в английской нумерации, 2 буквы. Эти буквы будут пропущены при разборе строки.st, nd, rd или th.
zНомер дня с начала года (начиная с нуля)C 0 по 365
Месяц
F и MТекстовое представление месяца, например January или SeptС January по December либо с Jan по Dec
m и nЧисловое представление месяца с первым нулем или без негоС 01 по 12 либо с 1 по 12
Год
YПолное числовое представление года, 4 цифрыПримеры: 1999 или 2003
y2 цифры в представлении года (в диапазоне 1970-2069 включительно)Примеры: 99 или 03 (будет расшифровано как 1999 и 2003 соответственно)
Время
a и AДо полудня и После полудняam или pm
g и h12-ти часовой формат времени с первым нулем или без негоС 1 по 12 либо с 01 по 12
G и H24-х часовой формат времени с нулем в начале или без негоС 0 по 23 или с 00 по 23
iМинуты с нулем в началеС 00 по 59
sСекунды с нулем в началеОт 00 до 59
uМикросекунды (до 6 цифр)Примеры: 45, 654321
Временная зона
e, O, P и TИдентификатор временной зоны, либо разница в часах относительно UTC, либо разница относительно UTC с запятой между часами и минутами, либо аббревиатура временной зоныПримеры: UTC, GMT, Atlantic/Azores или +0200 или +02:00 или EST, MDT
Дата/Время полностью
UКоличество секунд с начала Эпохи Unix (January 1 1970 00:00:00 GMT)Пример: 1292177455
Пробел и Разделители
(пробел)Один пробел или один отступ табулатурыПример:
#Один из следующих символов: ;, :, /, ., ,, , ( или )Пример: /
;, :, /, ., ,, , ( или )Символ разделитель.Пример:
?Один случайный (любой) символПример: ^ (Будьте внимательны: в UTF-8 кодировке вам может потребоваться более одного ?, так как там один символ может занимать более одного байта. В таких случаях может помочь использование *.
*Любое количество любых символов до следующего разделителяПример: * в Y-*-d для строки 2009-aWord-08 будет соответствовать aWord
!Приводит значения всех полей (год, месяц, день, час, минута, секунда, временная зона) ко времени начала Эпохи Unix.Без !, все поля будут соответствовать текущему времени.
|Приводит значения незаданных полей (год, месяц, день, час, минута, секунда, временная зона) ко времени начала Эпохи Unix.Y-m-d| установит год, месяц и день в соответствии с данными в строке, а часы, минуты и секунды установит в 0.
+Если задан этот спецификатор, данные, завершающие строку (нуль байт например) не будут вызывать ошибку, только предупреждениеИспользуйте DateTime::getLastErrors() для определения, были ли в строке завершающие символы.

Если format не содержит символ !, то значения полей, не заданных в строке формата, будут установлены в соответствии с текущим временем.

Если format содержит символ !, то значения полей, не заданных в строке формата (равно как и значения полей слева от !) будут установлены в соответствии со значениями полей начала Эпохи Unix.

Начало эпохи Unix 1970-01-01 00:00:00 UTC.

Строка, представляющая время.

Объект класса DateTimeZone, представляющий ожидаемую временную зону.

Если timezone не указан и time не содержит временную зону, то будет использована текущая временная зона.

Параметр timezone и текущая временная зона будут проигнорированы, если параметр time также содержит метку времени UNIX (т.е. timestamp вида 946684800) или же указанную временную зону (т.е. 2010-01-28T15:00:00+02:00).

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

Возвращает созданный экземпляр класса DateTime или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::createFromFormat()

Источник

DateTime::createFromFormat

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Описание

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

Для вставки в format буквенного символа, вы должны экранировать его с помощью обратного слеша( \ ).

Начало эпохи Unix 1970-01-01 00:00:00 UTC.

Строка, представляющая время.

Если timezone не указан или null и datetime не содержит часовой пояс, то будет использован текущий часовой пояс.

Параметр timezone и текущий часовой пояс будут проигнорированы, если параметр datetime также содержит метку времени UNIX (то есть timestamp вида 946684800 ) или же указанный часовой пояс (то есть 2010-01-28T15:00:00+02:00 ).

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

Возвращает созданный экземпляр класса DateTime или false в случае возникновения ошибки.

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

Примеры

Пример #1 Пример использования DateTime::createFromFormat()

Результат выполнения данных примеров:

Пример #2 Хитрости при использовании DateTime::createFromFormat()

Результатом выполнения данного примера будет что-то подобное:

Пример #3 Формат строки с буквенными символами

Результатом выполнения данного примера будет что-то подобное:

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

User Contributed Notes 27 notes

Be warned that DateTime object created without explicitely providing the time portion will have the current time set instead of 00:00:00.

Be aware:
If the day of the month is not provided, creating a DateTime object will produce different results depending on what the current day of the year is.
This is because the current system date will be used where values are not provided.

// on August 1st
printMonth ( «April» );
// outputs April

// on August 31st
printMonth ( «April» );
// outputs May
?>

In this case, each and every character on that string has to be escaped as shown below.

createFromFormat(‘U’) has a strange behaviour: it ignores the datetimezone and the resulting DateTime object will always have GMT+0000 timezone.

?>

The problem is microtime() and time() returning the timestamp in current timezone. Instead of using time you can use ‘now’ but to get a DateTimeObject with microseconds you have to write it this way to be sure to get the correct datetime:

Parsing RFC3339 strings can be very tricky when their are microseconds in the date string.

Since PHP 7 there is the undocumented constant DateTime::RFC3339_EXTENDED (value: Y-m-d\TH:i:s.vP), which can be used to output an RFC3339 string with microseconds:

Note: the difference between «v» and «u» is just 3 digits vs. 6 digits.

echo phpversion ();
// 7.2.7-1+ubuntu16.04.1+deb.sury.org+12019-01-102019-01-01

Reportedly, microtime() may return a timestamp number without a fractional part if the microseconds are exactly zero. I.e., «1463772747» instead of the expected «1463772747.000000». number_format() can create a correct string representation of the microsecond timestamp every time, which can be useful for creating DateTime objects when used with DateTime::createFromFormat():

If you’re here because you’re trying to create a date from a week number, you want to be using setISODate, as I discovered here:

Источник

date — Форматирует вывод системной даты/времени

Описание

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

Шаблон результирующей строки ( string ) с датой. См. параметры форматирования ниже. Также существует несколько предопределенных констант даты/времени, которые могут быть использованы вместо этих параметров. Например: DATE_RSS заменяет шаблон ‘D, d M Y H:i:s’.

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

Ошибки

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

Примеры

Пример #1 Примеры использования функции date()

// установка временной зоны по умолчанию. Доступно начиная с версии PHP 5.1
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’ );

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

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

Примечания

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

Источник

date_create

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Description

This function is an alias of: DateTime::__construct()

User Contributed Notes 10 notes

If you want to create the DateTime object directly from a timestamp use this

If you are getting an error like this:

Exception: DateTime::__construct(): Failed to parse time string (13/02/2013) at position 0 (1): Unexpected character in DateTime->__construct()

Note that when you create a new date object using a format with slashes and dashes (eg 02-02-2012 or 02/02/2012) it must be in the mm/dd/yy(yy) or mm-dd-yy(yy) format (rather than british format dd/mm/yy)! Months always before years (the american style) otherwise you’ll get an incorrect date and may get an error like the one above (where PHP is crashing on trying to decode a 13th month).

Can catch you off guard because everything seems to be working fine and dandy until you hit a value over 12.

= ‘Europe/Warsaw’ ; // +2 hours
$dateSrc = ‘2007-04-19 12:50’ ;

DateTime will recognise any number up to 12 as a [month], and any number up to 31 as a [day]; it calculates the resulting date to be [day] days after the start of [month]. This means that when a datetime object is created with more days than are found in that month, the date will be beyond the end of the month.

You should also be aware that DateTime has very lax date validation rules. It appears that all months have a maximum of 31 days.

For example, these will work fine:

= new DateTime ( ’02/31/2011′ );
$test = new DateTime ( ’06/31/2011′ );
?>

We all know that these dates are not real and are invalid so I think a good idea is to do some further validation on dates before creating a DateTime object with them.

@Marton Bodonyi
This is not exactly true.

The following code:
[code]
echo «1\n»;
print_r(date_create(’13-02-2013′));
echo «2\n»;
print_r(date_create(’13/02/2013′));
echo «3\n»;
print_r(new DateTime(’13-02-2013′));
echo «4\n»;
print_r(new DateTime(’13/02/2013′));
[/code]

produces the following output:
[code]
1
DateTime Object
(
[date] => 2013-02-13 00:00:00.000000
[timezone_type] => 3
[timezone] => Europe/London
)
2
3
DateTime Object
(
[date] => 2013-02-13 00:00:00.000000
[timezone_type] => 3
[timezone] => Europe/London
)
4

Fatal error: Uncaught exception ‘Exception’ with message ‘DateTime::__construct(): Failed to parse time string (13/02/2013) at position 0 (1): Unexpected character’ in /test.php:23
Stack trace:
#0 /test.php(23): DateTime->__construct(’13/02/2013′)
#1


thrown in /test.php on line 23

Which means that only slashes format actually wants you to use American order of date parts.
Hence you should use ‘dd-mm-yyyy’ or ‘mm/dd/yyyy’
Which is weird, and should not be such.

PHP version is 5.4.40

Notice php by default assume the give string as such format:
‘-‘ is ‘y-m-d’
‘/’ is ‘m/d/y’

Unless the given string has Y or M,
that is year is written as full year ‘2019’, or month is written as English shorthand ‘Jan’,
the default assumption will be applied, where the date might be incorrect.

The following code show a quick test: (true as of php 7.2)
$date = [
‘2019-1-3’,
’19-1-3′,
‘3-1-2019’,
‘3-Jan-19’,
‘3-1-19’, //php assume as y-m-d not d-m-y

‘2019/3/1’,
’19/3/1′, //fail, php think is month 19
‘1/3/2019’, //php think is m/d/y
‘1/3/19’
];

Источник

Php date create from format

(PHP 4, PHP 5, PHP 7, PHP 8)

date — Format a local time/date

Description

Parameters

Return Values

Errors/Exceptions

Every call to a date/time function will generate a E_WARNING if the time zone is not valid. See also date_default_timezone_set()

Changelog

ВерсияОписание
5.1.0Допустимым диапазоном дат для временных меток обычно являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Они соответствуют минимальному и максимальному значению 32-битного целого числа со знаком). Однако для PHP версии ниже 5.1.0 в некоторых операционных системах (например, Windows) этот диапазон был ограничен датами 01-01-1970 до 19-01-2038.
5.1.0
VersionDescription
8.0.0timestamp is nullable now.

Examples

Example #1 date() examples

// set the default timezone to use.
date_default_timezone_set ( ‘UTC’ );

// Prints something like: Monday
echo date ( «l» );

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$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 (the MySQL DATETIME format)
?>

Notes

See Also

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:

Источник

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

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