php create date from string
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_create_from_format
Описание
Создает и возвращает экземпляр класса DateTime, соответствующий заданному формату.
Список параметров
Символ в строке 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 |
y | 2 цифры в представлении года (в диапазоне 1970-2069 включительно) | Примеры: 99 или 03 (будет расшифровано как 1999 и 2003 соответственно) |
Время | — | — |
a и A | До полудня и После полудня | am или pm |
g и h | 12-ти часовой формат времени с первым нулем или без него | С 1 по 12 либо с 01 по 12 |
G и H | 24-х часовой формат времени с нулем в начале или без него | С 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::__construct
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
Описание
Создаёт и возвращает новый экземпляр класса DateTime.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.
Возвращаемые значения
Возвращает созданный объект класса DateTime. Процедурный стиль возвращает false в случае возникновения ошибки.
Ошибки
Список изменений
Версия | Описание |
---|---|
7.1.0 | Теперь микросекунды будут заполняться корректным значением, а не ‘00000’. |
Примеры
Пример #1 Пример использования DateTime::__construct()
Результат выполнения данных примеров:
Пример #2 Хитрости при использовании DateTime::__construct()
Результатом выполнения данного примера будет что-то подобное:
Смотрите также
User Contributed Notes 18 notes
The theoretical limits of the date range seem to be «-9999-01-01» through «9999-12-31» (PHP 5.2.9 on Windows Vista 64):
Note that the DateTime ctor also accepts boolean false and empty strings, and treats them the same as NULL (i.e. result is current date and time). This may lead to unexpected results if you forward function return values without explicitly checking them first.
Empty arrays and boolean true trigger PHP warnings OTOH.
(checked with PHP 5.5.18)
// New Timezone Object
$timezone = new DateTimeZone ( ‘America/New_York’ );
It is worth noting:
If you have not setup a default timezone, an Exception (or error if PHP
If time cannot be parsed an exception of type Exception is thrown which can be caught, however an E_WARNING is emitted as well. This might be confusing if you are converting warnings to exceptions in your error or shutdown handler.
Be careful working with MySQL dates representing point of transition to Daylight Saving Time.
The constructor of DateTime will convert timezone abbreviation to DST but not the time.
= new DateTimeZone ( ‘Europe/Sofia’ );
$transitionToDst = ‘2014-03-30 03:00:00’ ;
Watch out – this means that these two are NOT equivalent, they result in different timezones (unless your current timezone is GMT):
About constructing a DateTime, instead of just using the year it seems working when date matches the pattern «YYYY-MM»
— Returns the year correctly: «YYYY-MM»
— Ignores the given input and returns the year from NOW: «YYYY»
RESULTS/SCOPE:
— Linux (May 24, 2019)
— PHP 7.2.17 (cli)
Using this in a try catch to verify a string is in a valid date format is unreliable. Single letter strings used for the first argument (time string) of the constructor allows a new instance of the class to be created, without any exception or error.
I’m surprised this hasn’t been mentioned, but when constructing a DateTime with just the year as a string, DateTime will pre-initialize itself with NOW and then replace the year, so if today is 7/12/2016:
print((new DateTime ( ‘2015’ ))-> modify ( ‘+1 day’ )-> format ( ‘Y-m-d’ ));
?>
results in 2016-07-13
This seems to work as expected, at least now:
Also forgot to mention, that MySQL «zeroed» dates do not throw an error but produce a non-sensical date:
?>
Another good reason to write your own class that extends from DateTime.
When passing a non US or SQL date string the date will be formatted incorrectly.
// UK date d/m/Y.
$date_time = «08/03/2016 00:00:00»;
$dt = new DateTime($date_time, new DateTimeZone(«Europe/London»));
Impossible times due to daylight savings are handled by this function in a way similar to impossible dates, with the difference that this is not an error (i.e. a consequent call to DateTime::getLastError() yields nothing).
For example:
In the timezone «Europe/Berlin» on Sunday, March 30 2014 there was no 02:30 am, because that our is being skipped due to daylight savings on that day.
/*
Yields:
array(4) <
‘warning_count’ =>
int(0)
‘warnings’ =>
array(0) <
>
‘error_count’ =>
int(0)
‘errors’ =>
array(0) <
>
>
The impossible time ‘2014-03-30T02:30:00’ is interpreted as: 2014-03-30T03:30:00+0200
*/
?>
That is similar to how, for example, Febuary 29, 2014 would be handled, which would be interpreted as March 1, 2014. The difference is, that with the date that would be an error, with the time it is not.
Ambigous times due to daylight savings are handled as the second possibility. For example the time 2:30 am occurred twice on October 26, 2014 in the timezone «Europe/Berlin».
/*
Yields:
The ambiguous time ‘2014-10-26T02:30:00’ is interpreted as: 2014-10-26T02:30:00+0100
*/
?>
Note that «2014-10-26T02:30:00+0200», one hour earlier, would be a correct answer as well.
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 create date from string
(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: