Перевод даты в строку php
В распределенных системах, таких, как Интернет, время играет особую роль. Из-за незначительного расхождения системных часов игрок на рынке Forex может потерять десятки тысяч долларов в течение нескольких минут; система деловой разведки ошибется в составлении прогноза; серверы NNTP в процессе синхронизации потеряют важную информацию, нужную пользователю и т.д.
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
a | Включено обозначение «am» или «pm» |
A | Включено обозначение «AM» или «PM» |
d | День месяца (01-31) |
D | Сокращенное название дня недели (три буквы) |
F | Полное название месяца |
g | Часы (12-часовой формат без ведущих нулей) |
G | Часы (24-часовой формат без ведущих нулей) |
h | Часы (12-часовой формат) |
H | Часы (24-часовой формат) |
i | Минуты (00-59) |
j | День месяца без ведущих нулей (1-31) |
l | Полное название дня недели |
L | Признак високосного года (0 или 1) |
m | Месяц (01-12) |
M | Сокращенное название месяца (три буквы) |
n | Месяц (1-12) |
s | Секунды (00-59) |
t | Количество дней в данном месяце (от 28 до 31) |
U | Абсолютное время |
w | Номер дня недели (0 — воскресенье, 6 — суббота) |
y | Год (два разряда) |
Y | Год (четыре разряда) |
z | День года (0-365) |
Z | Смещение часового пояса в секундах (от -43200 до 43200) |
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку. Если в строку формата нужно добавить символы, которые сами по себе являются кодами формата, то перед ними надо поставить обратную косую черту «\». Символы, которые становятся кодами формата при добавлении к ним обратной косой, нужно предварять двумя косыми. Например, если необходимо добавить в строку «n», то надо ввести «\\n», поскольку «\n» является символом новой строки.
Пример 2
mktime( ) — возвращает абсолютное время, которое затем можно использовать с функциями date() или getdate(). Принимает до шести целочисленных аргументов в следующем порядке:
часы
минуты
секунды
месяц
день месяца
год
Пример 3
Внимание! Дата может находиться в допустимом диапазоне, но остальные функции работы с датами не примут это значение. Так, нельзя использовать mktime() для годов до 1902, а также следует использовать ее осторожно для годов до 1970.
strftime( ) — формирование локальной даты и времени. Аргументы: строка формата и абсолютное время. Второй аргумент необязателен. Возвращает строку с заданной или текущей датой в указанном формате. При этом названия месяцев и дней недели извлекается из локали, выбранной с помощью функции setlocate( ) Строка формата может содержать следующие коды:
%a | Сокращенное название дня недели |
%A | Полное название дня недели |
%b | Сокращенное название месяца |
%B | Полное название месяца |
%c | Предпочтительный формат даты и времени |
%C | Номер века |
%d | День месяца (1-31) |
%D | То же, что и %m/%d/%y |
%e | Месяц (1-12) |
%h | То же, что и %b |
%H | Часы (24-часовой формат) |
%I | Часы (12-часовой формат) |
%j | День года (0-365) |
%m | Месяц (1-12) |
%M | Минуты |
%n | Символ новой строки |
%p | Включено обозначение «am» или «pm» |
%r | Время с использованием a.m./p.m.-нотации |
%R | Время в 24-часовом формате |
%S | Секунды (00-59) |
%t | Символ табуляции |
%T | То же, что и %H:%M:%S |
%u | Номер дня недели (1 — понедельник, 7 — воскресенье) |
%U | Номер недели. Отсчет начинается с первого воскресенья года |
%V | Номер недели по ISO 8601:1988. Первая неделя должна иметь не менее четырех дней, а понедельник считается первым днем |
%W | Номер недели. Отсчет начинается с первого понедельника года |
%w | Номер дня недели (0 — воскресенье, 6 — суббота) |
%x | Предпочтительный формат даты без времени |
%X | Предпочтительный формат времени без даты |
%y | Год (два разряда) |
%Y | Год (четыре разряда) |
%Z | Часовой пояс (имя или сокращение) |
%% | Символ «%» |
Любая другая информация, включенная в строку формата, будет вставлена в возвращаемую строку.
strtotime
strtotime — Преобразует текстовое представление даты на английском языке в метку времени Unix
Описание
Первым параметром функции должна быть строка с датой на английском языке, которая будет преобразована в метку времени Unix (количество секунд, прошедших с 1 января 1970 года 00:00:00 UTC) относительно метки времени, переданной в now , или текущего времени, если аргумент now опущен.
Временная метка Unix, которую возвращает эта функция, не содержит информацию о часовых поясах. Для выполнения расчетов с информацией о дате/времени вы должны использовать более подходящий DateTimeImmutable.
Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания временной зоны различными способами.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.
Временная метка, используемая в качестве базы для вычисления относительных дат.
Возвращаемые значения
Возвращает временную метку в случае успеха, иначе возвращается FALSE .
Ошибки
Каждый вызов к функциям даты/времени при неправильных настройках временной зоны сгенерирует ошибку уровня E_NOTICE , и/или ошибку уровня E_STRICT или E_WARNING при использовании системных настроек или переменной окружения TZ . Смотрите также date_default_timezone_set()
Примеры
Пример #1 Пример использования функции strtotime()
Пример #2 Проверка ошибок
// до PHP 5.1.0 вместо false необходимо было сравнивать со значением -1
if (( $timestamp = strtotime ( $str )) === false ) <
echo «Строка ( $str ) недопустима» ;
> else <
echo » $str == » . date ( ‘l dS \o\f F Y h:i:s A’ , $timestamp );
>
?>
Примечания
Если количество лет указано двумя цифрами, то значения 00-69 будут считаться 2000-2069, а 70-99 — 1970-1999. Смотрите также замечания ниже о возможных различиях на 32-битных системах (допустимые даты заканчиваются 2038-01-19 03:14:07).
Корректным диапазоном временных меток обычно являются даты с 13 декабря 1901 20:45:54 UTC по 19 января 2038 03:14:07 UTC. (Эти даты соответствуют минимальному и максимальному значению 32-битового знакового целого).
Кроме того, до PHP 5.1.0, не все платформы поддерживают отрицательные метки времени, поэтому поддерживаемый диапазон дат может быть ограничен эпохой Unix. Это означает, что даты ранее 1 января 1970 г. не будут работать в Windows, некоторых дистрибутивах Linux и нескольких других операционных системах.
В 64-битных версиях PHP корректный диапазон временных меток фактически бесконечен, так как 64 битов хватит для представления приблизительно 293 миллиарда лет в обоих направлениях.
Даты в формате m/d/y или d-m-y разрешают неоднозначность с помощью анализа разделителей их элементов: если разделителем является слеш ( / ), то дата интерпретируется в американском формате m/d/y , если же разделителем является дефис ( — ) или точка ( . ), то подразумевается использование европейского формата d-m-y . Однако, если, год указан в двухзначном формате, а разделителем является дефис ( — ), строка даты интерпретируется как y-m-d .
Чтобы избежать потенциальной неоднозначности, рекомендуется использовать даты в формате стандарта ISO 8601 ( YYYY-MM-DD ), либо пользоваться функцией DateTime::createFromFormat() там, где это возможно.
Не рекомендуется использовать эту функцию для математических операций. Целесообразно использовать DateTime::add() и DateTime::sub() начиная с PHP 5.3, или DateTime::modify() в PHP 5.2.
Смотрите также
- Форматы даты и времени
- DateTime::createFromFormat() — Разбирает строку с датой согласно указанному формату
- checkdate() — Проверяет корректность даты по григорианскому календарю
- strptime() — Разбирает строку даты/времени, сгенерированную функцией strftime
User Contributed Notes 39 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.
echo date ( «jS F, Y» , strtotime ( «11.12.10» ));
// outputs 10th December, 2011
echo date ( «jS F, Y» , strtotime ( «11/12/10» ));
// outputs 12th November, 2010
echo date ( «jS F, Y» , strtotime ( «11-12-10» ));
// outputs 11th December, 2010
?>
Hope this helps someone!
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.
echo date ( «Y-m-d» , strtotime ( «2009-01-31 +1 month» ) ); // PHP: 2009-03-03
echo date ( «Y-m-d» , strtotime ( «2009-01-31 +2 month» ) ); // PHP: 2009-03-31
?>
( ‘2009-01-31’ , INTERVAL 1 MONTH ); // MySQL: 2009-02-28
?>
UK dates (eg. 27/05/1990) won’t work with strotime, even with timezone properly set.
/*
However, if you just replace «/» with «-» it will work fine.
= strtotime ( str_replace ( ‘/’ , ‘-‘ , ’27/05/1990’ ));
?>
*/
[red., derick]: What you instead should do is:
= date_create_from_format ( ‘d/m/y’ , ’27/05/1990′ );
?>
That does not make it a timestamp, but a DateTime object, which is much more versatile instead.
exemplo strtotime(date(«Y-m-d») . «+1month»);
A strtotime também funciona quando concatenamos strings,
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.
= new DateTime ( ‘2010-01-31’ );
$d -> modify ( ‘next month’ );
echo $d -> format ( ‘F’ ), «\n» ;
?>
In the above, using «next month» on January 31 will output «March» even though you might want it to output «February». («+1 month» will give the same result. «last month», «-1 month» are similarly affected, but the results would be seen at beginning of March.)
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»:
= new DateTime ( ‘2010-01-08’ );
$d -> modify ( ‘first day of next month’ );
echo $d -> format ( ‘F’ ), «\n» ;
?>
= new DateTime ( ‘2010-01-08’ );
$d -> modify ( ‘first day of +1 month’ );
echo $d -> format ( ‘F’ ), «\n» ;
?>
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.
Incorrect:
echo date ( «jS F, Y» , strtotime ( «11.12.10» ));
// outputs 10th December, 2011
echo date ( «jS F, Y» , strtotime ( «11/12/10» ));
// outputs 12th November, 2010
echo date ( «jS F, Y» , strtotime ( «11-12-10» ));
// outputs 11th December, 2010
?>
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.***
Therefore, the above code does not work on 2 digit years — only 4 digit years
The difference between ‘today’ and ‘now’ is the former strips off the time (setting it to 00:00, ie. midnight just past), and the latter includes the time — assuming UTC unless specified otherwise.
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:
$listIt = (strtotime($end_date) >= strtotime(‘today’) ? 1 : 0);
where $end_date is the final date in a show series. So if tonight’s show is the last, it will stay on the web page until 00:00 tomorrow.
I don’t normally include performance times in the date field because some shows have matinées, others don’t — so I use a free-form performance time field in the CMS instead (where even ‘Time: TBD’ is allowed). [The only instance where I DO include the time is when there are two different shows on the same day, to ensure they appear in chronological order.]
So strtotime($end_date) will always return the timestamp at 00:00 that day. If I instead used:
$listIt = (strtotime($end_date) >= strtotime(‘now’) ? 1 : 0);
the function would return $listIt = 0 at all times today — something I don’t want.
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
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 ( date ( «l» , strtotime ( » $thisMonth $thisYear » ))== ‘Tuesday’ ) <
echo «
This month starts on a Tuesday. Use \» $thisMonth $thisYear \» to check for first Tuesday.
This month does not start on a Tuesday. Use \»first tuesday $thisMonth $thisYear \» to check for first Tuesday.
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):
> The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
Therefore strtotime(‘@-1000’) returns 1000 seconds before the epoch.
Here’s a hack to make this work for MS SQL’s datetime junk, since strtotime() has issues with fractional seconds.
= «Feb 7 2009 09:48:06:697PM» ;
$newDatetime = preg_replace ( ‘/:454/’ , » , $MSSQLdatetime );
$time = strtotime ( $newDatetime );
echo $time . «\n» ;
[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?
If you want the timestamp of the start of the ISO Week (i.e. on Monday) as defined by ISO 8601, you can use this one liner:
= strtotime ( date ( ‘o-\\WW’ )); //
?>
You can also find out the start of week of any time and format it into an ISO date with another one liner like this:
= date ( ‘Y-m-d’ , strtotime ( date ( ‘o-\\WW’ , $time )));
?>
For more information about ISO-8601 and ISO week date:
http://en.wikipedia.org/wiki/ISO_8601#Week_dates
http://en.wikipedia.org/wiki/ISO_week_date
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.
= date ( «r» );
$atom = date ( «c» );
$human1 = date ( ‘m/d/Y’ , strtotime ( $rss ));
$human2 = date ( ‘m/d/Y’ , strtotime ( $atom ));
echo $rss . «
» . $atom . «
» . $human1 . «
» . $human2 ;
?>
Adding a note to an already long page:
Try to be as specific as you can with the string you pass in. For example
echo date ( ‘F’ , strtotime ( ‘February’ ));
?>
is not specific enough. Depending on the day of the month, you may get a different response. For a non-leap year, you’ll get March if the _current day of the month_ is the 29th, 30th or 31st. If it’s a leap year, you’ll get March on the 30th or 31st of the month. The same thing will happen on the 31st of any month when you pass in the name of any month with less than 31 days. This happens because the strtotime() function will fill in missing parts from the current day.
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.
I was having trouble parsing Apache log files that consisted of a time entry (denoted by %t for Apache configuration). An example Apache-date looks like: [21/Dec/2003:00:52:39 -0500]
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.
function from_apachedate ( $date )
<
list( $d , $M , $y , $h , $m , $s , $z ) = sscanf ( $date , «[%2d/%3s/%4d:%2d:%2d:%2d %5s]» );
return strtotime ( » $d $M $y $h : $m : $s $z » );
>
?>
Hope it helps anyone else seeking such a conversion.
This function DOES NOT work from left-to-right as one would think. This function parses the string as a whole, then applies the intervals by size (year, month, . ). Take the following example:
= strtotime ( ‘2011-02-22’ ); // February 22nd, 2011. 28 days in this month, 29 next year.
echo date ( ‘n/j/Y’ , strtotime ( ‘+1 year, +7 days’ , $Date )); // add 1 year and 7 days. prints 2/29/2012
echo «
» ;
echo date ( ‘n/j/Y’ , strtotime ( ‘+7 days, +1 year’ , $Date )); // add 7 days and 1 year, but this also prints 2/29/2012
echo «
» ;
echo date ( ‘n/j/Y’ , strtotime ( ‘+1 year’ , strtotime ( ‘+7 days’ , $Date ))); // this prints 3/1/2012, what the 2nd would do if it was left-to-right
?>
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’
We can get timestamp from RFC 2822:
= strtotime ( ‘Mon, 30 Jun 2014 11:30:00 +0400’ ); // timestamp from RFC 2822
echo date ( ‘Y-m-d H:i:s’ , $time ); // 2014-06-30 10:30:00
One important thing you should remember is that the timestamp value returned by time() is time-zone agnostic and gets the number of seconds since 1 January 1970 at 00:00:00 UTC. This means that at a particular point in time, this function will return the same value in the US, Europe, India, Japan, .
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:
function UTCdatestringToTime ( $utcdatestring )
<
$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );
$result = strtotime ( $utcdatestring );
date_default_timezone_set ( $tz );
return $result ;
>
?>
Test:
= ‘Europe/Amsterdam’ ;
$utctime = ‘2018-12-06T09:04:55’ ;
if (! date_default_timezone_set ( $tz )) <
WriteLine ( ‘Setting default timezone to ‘ . $tz . ‘ failed’ );
die;
>
WriteLine ();
WriteLine ( ‘Default timezone set to ‘ . $tz );
WriteLine ( ‘UTC time: ‘ . $utctime );
WriteLine ();
WriteLine ( ‘[ UTCdatestringToTime ]’ );
$phptime = UTCdatestringToTime ( $utctime );
WriteLine ( ‘PHP time: ‘ . $phptime );
WriteTime ( $phptime , true );
WriteTime ( $phptime , false );
WriteLine ();
WriteLine ( ‘——————————————————————————-‘ );
WriteLine ( ‘[ strtotime($utctime) — Converts $utctime as if it was in timezone ‘ . $tz . ‘ because the string has no timezone specification ]’ );
$phptime = strtotime ( $utctime ); //Seconds since the unix epoch
WriteLine ( ‘PHP time: ‘ . $phptime );
WriteTime ( $phptime , true );
WriteTime ( $phptime , false );
function WriteLine ( $text = » )
<
echo $text . «\r\n» ;
>
function WriteTime ( $time , bool $asUTC )
<
$tz = date_default_timezone_get ();
if ( $asUTC ) date_default_timezone_set ( ‘UTC’ );
WriteLine ( ‘—> (‘ . date_default_timezone_get () . ‘) ‘ . date ( ‘Y-m-d H:i:s’ , $time ));
if ( $asUTC ) date_default_timezone_set ( $tz );
>
?>
Test output:
Default timezone set to Europe / Amsterdam
UTC time : 2018 — 12 — 06T09 : 04 : 55
[ UTCdatestringToTime ]
PHP time : 1544087095
—> ( UTC ) 2018 — 12 — 06 09: 04 : 55
—> ( Europe / Amsterdam ) 2018 — 12 — 06 10 : 04 : 55
——————————————————————————-
[ strtotime ( $utctime ) — Converts $utctime as if it was in timezone Europe / Amsterdam because the string has no timezone specification ]
PHP time : 1544083495
—> ( UTC ) 2018 — 12 — 06 08: 04 : 55
—> ( Europe / Amsterdam ) 2018 — 12 — 06 09: 04 : 55
*/
?>
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.
strtotime(«0000-00-00 00:00:00») returns FALSE on a 32 bit system.
strtotime(«0000-00-00 00:00:00») returns -62169955200 on a 64 bit system.
Be carefull with weekdays names
echo date ( ‘r’ , strtotime ( «Thursday 01:15» )), «\n» ; ?>
returns something like «Thu, 17 Mar 2016 01:15:00 +0200»
but
echo date ( ‘r’ , strtotime ( «Thursdays 01:15» )), «\n» ; ?>
returns «Thu, 17 Mar 2016 09:15:00 +0200».
So «s» at end mean «+8 hours».
Strtotime() can be used to loop through date range.
as follows
= strtotime ( ‘2009-02-01’ );
$end = strtotime ( ‘2009-03-10’ );
$date = $start ;
while( $date $end )
<
//write your code here
$date = strtotime ( «+1 day» , $date );( counter )
NOTE: strtotime returns different values when the Week day does not match the date.
= strtotime ( «26 Oct 0010 12:00:00 +0100» );
$d2 = strtotime ( «Tue, 26 Oct 0010 12:00:00 +0100» );
$d3 = strtotime ( «Sun, 26 Oct 0010 12:00:00 +0100» ); //But Oct 26 is a Tuesday, NOT a Sunday.
echo $d1 ; //ok 1288090800 that is «26 Ott 2010 — 11:00»;
echo $d2 ; //ok 1288090800 that is «26 Ott 2010 — 11:00»;
echo $d3 ; //WRONG! 1288522800 that is «31 Ott 2010 — 11:00»;
?>
Sometime I found RSS feeds that contains week days that do not match the date.
A possible solution is to remove useless week day before passing the date string into strtotime, example:
= «Sun, 26 Oct 0010 12:00:00 +0100» ;
if( ( $comma_pos = strpos ( $date_string , ‘,’ )) !== FALSE )
$date_string = substr ( $date_string , $comma_pos + 1 );
$d3 = strtotime ( $date_string );
?>
// small function auto detect to convert date
function formatDate($date)
<
if (strpos($date,’/’) !== false) :
$date = str_replace(‘/’, ‘-‘, $date);
$date = date(‘Y-m-d h:i:s’, strtotime($date));
else :
$date = date(‘d-m-Y h:i:s’, strtotime($date));
$date = str_replace(‘-‘, ‘/’, $date);
endif;
return $date;
>
Be aware that if you are running 5.2.8, there is a memory leak with this function and it could cost someone valuable time finding out what the problem was. Per usual, running the latest (minor) version tends to be a good idea.