Php parse date from string

date_parse

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

date_parse — Возвращает ассоциативный массив с подробной информацией о заданной дате/времени

Описание

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

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

Возвращает массив ( array ), содержащий информацию о дате/времени в случае успешного выполнения или false в случае возникновения ошибки.

Ошибки

В случае возникновения ошибок форматирования даты/времени, элемент массива ‘errors’ будет содержать сообщения об этих ошибках.

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

Примеры

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

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

Относительные форматы не влияют на значения, разобранные из абсолютных форматов, но будут доступны в элементе массива с ключом «relative».

Пример #2 date_parse() с относительным форматом

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

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

User Contributed Notes 11 notes

/*Returns:
array(12) <
[«year»]=> int(2010)
[«month»]=> int(2)
[«day»]=> int(1) // bool(false)
[«minute»]=> bool(false)
[«second»]=> bool(false)
[«fraction»]=> bool(false)
[«warning_count»]=> int(0)
[«warnings»]=> array(0) < >
[«error_count»]=> int(0)
[«errors»]=> array(0) < >
[«is_localtime»]=> bool(false)
>*/
?>

Be aware that date_parse() is happy with just a time zone and it can be pretty counter-intuitive. E.g.:

( date_parse ( ‘Europe/Madrid’ ) );
?>

. prints an array where year, month, day. are FALSE. But so do these:

( date_parse ( ‘A’ ) );
var_dump ( date_parse ( ‘B’ ) );
var_dump ( date_parse ( ‘X’ ) );
?>

Don’t forget to further validate date_parse()’s output even when it isn’t FALSE and the ‘errors’ key is empty.

Here is a workaround for the «Feb 2010» problem. It also handles «2014».

It’s sometimes useful to be able to store incomplete dates, for example when all you know of someone’s birthdate is the year or the month and day.

date_parse() handles (and MySQL accepts) dates containing zero-value elements such as «2017-00-00» and «0000-03-29», leaving it up to the parent application to determine when to require and how to handle missing date elements. date_parse() correctly reports zero values for zero-value date elements, reports an ‘invalid date’ warning, and does not report an error.

[ error_count ] => 0
[ errors ] => Array
(
)

[ error_count ] => 0
[ errors ] => Array
(
)

[ is_localtime ] =>
)
?>

However, simply omitting date elements gives PHP too much discretion in second-guessing our intentions:

[ error_count ] => 0
[ errors ] => Array
(
)

Similarly, this feature of accepting zero date elements does not carry over to timestamps:

Array
(
[ seconds ] => 0
[ minutes ] => 0
[ hours ] => 0
[ mday ] => 28
[ wday ] => 2
[ mon ] => 2
[ year ] => 2017
[ yday ] => 58
[ weekday ] => Tuesday
[ month ] => February
[ 0 ] => 1488268800
)
?>
In this case, PHP interprets the «zeroth» day of March to be the last day of February.

Источник

parse a date string

I have this string in a post variable

I need to parse it via php and turn it into this format

I am using php and i need this format so i can run this query

Php parse date from string. Смотреть фото Php parse date from string. Смотреть картинку Php parse date from string. Картинка про Php parse date from string. Фото Php parse date from string

8 Answers 8

If you want to handle it in PHP, your best bet is to use the strtotime() function which converts a string into a time that can then be manipulated with the date() function.

So you’d do something like:

The nice thing about using strtotime() is that you don’t have to worry about the exact format of the string you pass in. As long as it’s something semi-reasonable, it’ll will convert it.

So it would handle 03/21/2011, 3-21-2011, 03-21-11 without any modifications or special cases.

You can parse it even from mysql

Php parse date from string. Смотреть фото Php parse date from string. Смотреть картинку Php parse date from string. Картинка про Php parse date from string. Фото Php parse date from string

That should do what you need.

Php parse date from string. Смотреть фото Php parse date from string. Смотреть картинку Php parse date from string. Картинка про Php parse date from string. Фото Php parse date from string

While there are many ways to do this, I think the easiest to understand and apply to all date conversions is:

It is explicit and you’ll never have to wonder about m/d or d/m, etc.

You can see it here

Or use the Date class of PHP 5.3

STR_TO_DATE(created_at, ‘%m/%d/%Y’) as ‘Original Date Submitted’.

Php parse date from string. Смотреть фото Php parse date from string. Смотреть картинку Php parse date from string. Картинка про Php parse date from string. Фото Php parse date from string

You can use something like this

If you the data comes in a format that is not supported. For instance when trying to parse a date in a non-US date format meaning the month and day are switched but the format uses forward slashes (21/04/78) Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

To really make your code clear as to which date you are parsing and to validate that the data coming in as using the correct format, I would use date_create_from_format. Here is some code to help:

This example is explained in more full detail at this link:

Источник

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:

Источник

strtotime

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

strtotime — Преобразует текстовое представление даты на английском языке в метку времени Unix

Описание

Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания часового пояса различными способами.

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

Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.

Временная метка, используемая в качестве базы для вычисления относительных дат.

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

Ошибки

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

ВерсияОписание
8.0.0baseTimestamp теперь допускает значение null.

Примеры

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

Пример #2 Проверка ошибок

Примечания

Корректным диапазоном временных меток обычно являются даты с 13 декабря 1901 20:45:54 UTC по 19 января 2038 03:14:07 UTC. (Эти даты соответствуют минимальному и максимальному значению 32-битового знакового целого).

В 64-битных версиях PHP корректный диапазон временных меток фактически бесконечен, так как 64 битов хватит для представления приблизительно 293 миллиарда лет в обоих направлениях.

Чтобы избежать потенциальной неоднозначности, рекомендуется использовать даты в формате стандарта ISO 8601 ( YYYY-MM-DD ), либо пользоваться функцией DateTime::createFromFormat() там, где это возможно.

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

User Contributed Notes 42 notes

I’ve had a little trouble with this function in the past because (as some people have pointed out) you can’t really set a locale for strtotime. If you’re American, you see 11/12/10 and think «12 November, 2010». If you’re Australian (or European), you think it’s 11 December, 2010. If you’re a sysadmin who reads in ISO, it looks like 10th December 2011.

The best way to compensate for this is by modifying your joining characters. Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

The «+1 month» issue with strtotime
===================================
As noted in several blogs, strtotime() solves the «+1 month» («next month») issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.

A strtotime também funciona quando concatenamos strings,

UK dates (eg. 27/05/1990) won’t work with strotime, even with timezone properly set.

[red., derick]: What you instead should do is:

WARNING when using «next month», «last month», «+1 month», «-1 month» or any combination of +/-X months. It will give non-intuitive results on Jan 30th and 31st.

The way to get what people would generally be looking for when they say «next month» even on Jan 30 and Jan 31 is to use «first day of next month»:

strtotime() also returns time by year and weeknumber. (I use PHP 5.2.8, PHP 4 does not support it.) Queries can be in two forms:
— «yyyyWww», where yyyy is 4-digit year, W is literal and ww is 2-digit weeknumber. Returns timestamp for first day of week (for me Monday)
— «yyyy-Www-d», where yyyy is 4-digit year, W is literal, ww is 2-digit weeknumber and dd is day of week (1 for Monday, 7 for Sunday)

// Get timestamp of 32nd week in 2009.
strtotime ( ‘2009W32’ ); // returns timestamp for Mon, 03 Aug 2009 00:00:00
// Weeknumbers strtotime ( ‘2009W01’ ); // returns timestamp for Mon, 29 Dec 2008 00:00:00
// strtotime(‘2009W1’); // error! returns false

// See timestamp for Tuesday in 5th week of 2008
strtotime ( ‘2008-W05-2’ ); // returns timestamp for Tue, 29 Jan 2008 00:00:00
?>

Weeknumbers are (probably) computed according to ISO-8601 specification, so doing date(‘W’) on given timestamps should return passed weeknumber.

I tried using sams most popular example but got incorrect results.

Then I read the notes which said:
if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. ***If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.***

I run a theatre’s website. Obviously, I need to ensure shows that have already happened do not appear on web pages, so I use something on the lines of:

So strtotime($end_date) will always return the timestamp at 00:00 that day. If I instead used:

You are not restricted to the same date ranges when running PHP on a 64-bit machine. This is because you are using 64-bit integers instead of 32-bit integers (at least if your OS is smart enough to use 64-bit integers in a 64-bit OS)

The following code will produce difference output in 32 and 64 bit environments.

32-bit PHP: bool(false)
64-bit PHP: int(-30607689600)

This is true for php 5.2.* and 5.3

Also, note that the anything about the year 10000 is not supported. It appears to use only the last digit in the year field. As such, the year 10000 is interpretted as the year 2000; 10086 as 2006, 13867 as 2007, etc

For negative UNIX timestamps, strtotime seems to return the literal you passed in, or it may try to deduct the number of seconds from today’s date.

To work around this behaviour, it appears that the same behaviour as described in the DateTime classes applies:

Specifically this line here (in the EN manual):

Therefore strtotime(‘@-1000’) returns 1000 seconds before the epoch.

It took me a while to notice that strtotime starts searching from just after midnight of the first day of the month. So, if the month starts on the day you search for, the first day of the search is actually the next occurrence of the day.

In my case, when I look for first Tuesday of the current month, I need to include a check to see if the month starts on a Tuesday.

If you want to confront a date stored into mysql as a date field (not a datetime) and a date specified by a literal string, be sure to add «midnight» to the literal string, otherwise they won’t match:

//I.E.: today is 17/02/2011

echo strtotime ( ‘2011-01-01’ ); //1293836400
echo strtotime ( ‘first day of last month’ ); //1293888128 Note: it’s different from the previous one, since it computes also the seconds passed from midnight. So this one is always greater than simple ‘2011-01-01’
echo strtotime ( ‘midnight first day of last monty’ ); //1293836400 Note: it’s the same as ‘2011-01-01’

Apache claims this to be a ‘standard english format’ time. strtotime() feels otherwise.

I came up with this function to assist in parsing this peculiar format.

strtotime is awesome for converting dates.
in this example i will make an RSS date, an
ATOM date, then convert them to a human
readable m/d/Y dates.

[red.: This is a bug, and should be fixed. I have file an issue]

This comment apply to PHP5+

We can now do thing like this with strtotime:
= strtotime ( ‘Monday this week’ );
?>
However this works based on a week starting Sunday. I do not know if we can tweak this PHP behavior, anyone know?

strtotime() will convert a string WITHOUT a timezone indication as if the string is a time in the default timezone ( date_default_timezone_set() ). So converting a UTC time like ‘2018-12-06T09:04:55’ with strtotime() actually yields a wrong result. In this case use:

Adding a note to an already long page:

Try to be as specific as you can with the string you pass in. For example

Assuming today is July 31, the timestamp returned by strtotime(‘February’) will ultimately be seen as February 31 (non-existant obviously), which then is interpreted as March 3, thus giving a month name of March.

Interestingly, adding the year or the day will give you back the expected month.

strtotime() produces different output on 32 and 64 bit systems running PHP 5.3.3 (as mentioned previously). This affects the «zero date» («0000-00-00 00:00:00») as well as dates outside the traditional 32 date range.

In modern 64-bit systems (tested on mac) the old 1970 to 2038 date range limitations are gone.

strtotime(«0001-10-30») gives int(-62109540728)
strtotime(«6788-10-30») gives int(152067506400)

Источник

parse_str

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

parse_str — Parses the string into variables

Description

Parses string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).

Parameters

If the second parameter result is present, variables are stored in this variable as array elements instead.

Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.

Return Values

No value is returned.

Changelog

VersionDescription
8.0.0result is no longer optional.
7.2.0Usage of parse_str() without a second parameter now emits an E_DEPRECATED notice.

Examples

Example #1 Using parse_str()

Because variables in PHP can’t have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with result parameter.

Example #2 parse_str() name mangling

Notes

All variables created (or values returned into array if second parameter is set) are already urldecode() d.

See Also

User Contributed Notes 31 notes

It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

# silently fails to handle multiple values
parse_str ( ‘foo=1&foo=2&foo=3’ );

# the above produces:
$foo = array( ‘foo’ => ‘3’ );
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

# bizarre php-specific behavior
parse_str ( ‘foo[]=1&foo[]=2&foo[]=3’ );

if you need custom arg separator, you can use this function. it returns parsed query as associative array.

You may want to parse the query string into an array.

As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.

This is a very useful combination if you want to re-use a search string url, but also slightly modify it:

Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest

(Array indexes are automatically created.)

CONVERT ANY FORMATTED STRING INTO VARIABLES

I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:

to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character. and i have comma separated values. so i replace comma with &

Note that the characters «.» and » » (empty space) will be converted to «_». The characters «[» and «]» have special meaning: They represent arrays but there seems to be some weird behaviour, which I don’t really understand:

Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.

?>

Note that the function will also append the session ID to the query string if it needs to be.

The array to be populated does not need to be defined before calling the function:

Источник

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

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