|
|
strftime (PHP 3, PHP 4, PHP 5) strftime -- Форматирует текущую дату/время с учетом текущей локали Описаниеstring strftime ( string format [, int timestamp] )
Возвращает строку, отформатированную в соответствии с аргументом
format, используя аргумент
timestamp или текущее системное время, если
этот аргумент не передан. Названия месяцев, дней недели и другие
строки, зависящие от языка, соответствуют текущей локали,
установленной функцией setlocale().
В форматирующей строке распознаются следующие символы:
%a - сокращенное название дня недели в текущей локали
%A - полное название дня недели в текущей локали
%b - сокращенное название месяца недели в текущей локали
%B - полное название месяца недели в текущей локали
%c - предпочтительный формат даты и времени в текущей локали
%C - столетие (год, деленный на 100 и огругленный до целого, от 00 до 99)
%d - день месяца в виде десятичного числа (от 01 до 31)
%D - аналогично %m/%d/%y
%e - день месяца в виде десятичного числа, если это одна цифра, то
перед ней добавляется пробел (от ' 1' до '31')
%g - подобно %G, но без столетия.
%G - Год, 4-значное число, соответствующее номеру недели по ISO (см. %V).
Аналогично %Y, за исключением того, что если номер недели по ISO
соответствует предыдущему или следующему году, используется
соответствующий год.
%h - аналогично %b
%H - номер часа от 00 до 23
%I - номер часа от 01 до 12
%j - номер дня в году (от 001 до 366)
%m - номер месяца (от 01 до 12)
%M - минуты
%n - символ "\n"
%p - `am' или `pm', или соответствующие строки в текущей локали
%r - время в формате a.m. или p.m.
%R - время в 24-часовом формате
%S - секунды
%t - символ табуляции ("\t")
%T - текущее время, аналогично %H:%M:%S
%u - номер дня недели от 1 до 7, где 1 соответствует понедельнику
| Внимание |
На Sun Solaris 1 соответствует воскресенью, хотя в ISO 9889:1999
(текущий стандарт языка C) явно указано, что это должен быть
понедельник.
|
%U - порядковый номер недели в текущем году. Первым днем первой
недели в году считается первое воскресенье года.
%V - Порядковый номер недели в году по стандарту ISO 8601:1988
от 01 до 53, где 1 соответствует первой неделе в году, в которой
как минимум 4 дня принадлежат этому году. Первым днем недели считается понедельник.
(Используйте %G or %g для определения соответствующего года)
%W - порядковый номер недели в текущем году. Первым днем первой
недели в году считается первый понедельник года.
%w - номер дня недели, 0 соответствует воскресенью
%x - предпочтительный формат даты без времени в текущей локали
%X - предпочтительный формат времени без даты в текущей локали
%y - год без столетия (от 00 до 99)
%Y - год, включая столетие
%Z - временная зона в виде смещения, аббривеатуры или полного
наименования
%% - символ `%'
Замечание:
strftime() использует функции операционной
системы, поэтому отдельные форматирующие символы могут не работать
в вашей операционной системе. Кроме того, не все платформы
поддерживают отрицательные метки времени
support negative timestamps. Это значит, что %e, %T, %R и %D (а
возможно и другие) и даты до Jan 1, 1970 не
поддерживаются Windows, некоторыми версиями Linux и некоторыми
другими операционными системами. Список форматирующих символов,
поддерживаемых Windows, можно найти на
сайте MSDN.
Пример 1. Пример использования функции strftime() с разными локалями |
<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" по-фински - %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" по-французски - %A и");
setlocale(LC_TIME, "de_DE");
echo strftime(" по-немецки - %A.\n");
?>
|
|
Этот пример будет работать, если на вашей системе установлены
соответствующие локали.
Замечание:
%G and %V, которые основаны на номере недели по ISO 8601:1988,
Могут давать результат, отличный от ожидаемого, если вы не
полностью понимаете систему нумерации, используемую этим
стандартом. Смотрите описание %V выше и следующий пример.
Пример 2. Пример номеров недели по ISO 8601:1988 |
<?php
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";
?>
|
|
См. также описание функций setlocale(),
mktime(), и
спецификацию strftime() Open Group.
josh dot helzer at gmail dot com
19-Sep-2007 07:39
If strlen($format) >= 1024, the output of strftime($format) is the empty string.
nielsvan den berge at hotmail dot com
31-Aug-2007 06:43
A small function to get the first weekday of the month.
For example the first monday of the month, or the first friday, etc.
<?php
function get_first_day($day_number=1, $month=false, $year=false)
{
$month = ($month === false) ? strftime("%m"): $month;
$year = ($year === false) ? strftime("%Y"): $year;
$first_day = 1 + ((7+$day_number - strftime("%w", mktime(0,0,0,$month, 1, $year)))%7);
return mktime(0,0,0,$month, $first_day, $year);
}
echo strftime("%a %d-%m-%Y", get_first_day(3, 1, 2007));
?>
ma
28-Aug-2007 05:58
note, that for some languages you MUST set LC_ALL instead of LC_TIME.
note that you further have to explicitly define your output-encoding (default is ISO-8859-1 [which makes problems for some languages])!
at least i expirienced this behaviour on a german WinXP-PHP4 environment:
<?php
setlocale(LC_TIME, 'RUS'); echo strftime('%A', time());
?>
<?php
header('Content-Type: text/html; charset=UTF-8'); echo setlocale(LC_ALL, 'RUS').': ';
echo iconv('windows-1251', 'UTF-8', strftime('%A', time()))."\n";
?>
ben dot holland at thirdlight dot com
21-Jun-2007 05:03
This little function allows you to provide a reasonably human readable string and convert to a timestamp - see example in comments below.
I find it far more useful than having to remember all the '%' modifiers. Am also well aware of its failings but it works in a lot of the real life situations I've come across.
<?php
function AmazingStringFromTime($str, $nTimestamp = null)
{
$arrPairs = array(
"DDDD" => "%A",
"DDD" => "%a",
"DD" => "%d",
"D" => "%e", "MMMM" => "%B",
"MMM" => "%b",
"MM" => "%m",
"YYYY" => "%Y",
"YY" => "%y",
"HH" => "%H",
"hh" => "%I",
"mm" => "%M",
"ss" => "%S",
);
$str = str_replace(array_keys($arrPairs), array_values($arrPairs), $str);
return strftime($str, $nTimestamp);
}
?>
judas dot iscariote at gmail dot com
21-Jan-2007 12:34
Security notice:
You can end with a (probably unexpected) XSS if the $format parameter is user submitted data ;)
<?php
echo strftime("<script>alert('lol');</script>");
?>
PHP does not check if $format is a valid format, so the usual security precautions should be taken here .
th1nk3r at gmail dot DELETETHIS dot com
20-Jan-2007 09:35
Function strftime() use the locales installed in your system (linux).
If you are like me and only leave in the system the locales you use normally (en_US and your own language locale, like es_ES), you'll only be able to use the locales installed. If your application is translated to other languages, you need these locales too.
The name of the locale in your system is important too. This can be a problem when you want to distribute the app.
If you have this locales in your system:
en_US/ISO-8859-1
en_US.UTF-8/UTF-8
es_ES/ISO-8859-1
es_ES@euro/ISO-8859-15
es_ES.UTF-8/UTF-8
es_ES@euro/UTF-8
and use setlocale('es_ES'), the result will use the iso-8859-1 charset even if you have all your system, files and configuration options in UTF-8. To receive content in UTF-8, in this example, you need to use setlocale('es_ES.UTF-8') or setlocale('es_ES.UTF-8@UTF-8').
The definition of locales can change from one system to another, and so the charset from the results.
commander at graphicore dot de
18-Dec-2006 09:18
Thats how I get the %G, %g ISO Year and %V Week with php 4.4.4 on Window$.
It works quite simple:
1. on January it can't be a week bigger than 51, thats what i've learned in school
2. on december many weeks have gone since the last New Year's Eve and therefore it cant be the first week of the year
i hope it saves time
<?php
function YearOfWeek($format,$date = NULL){
if(!isset($date)){
$date = time();
}
list ($G,$V,$month) = explode('_',date ('Y_W_m',$date));
if( ($month === '01') && ($V >= 52 ) ){
$G--;
}else if( ($month === '12') && ($V === '01') ){
$G++;
}
$g = substr($G, -2, 2);
$format = str_replace(array('%V','%G','%g'),array($V,$G,$g),$format);
return ($format);
}
$format = 'week %V of the year %G (%g), year %Y (%y)';
$date = mktime(0, 0, 0, 12, 31, 2008);
echo strftime(YearOfWeek($format,$date), $date) . "\n";
$date = mktime(0, 0, 0, 1, 1, 2010);
echo strftime(YearOfWeek($format,$date), $date) . "\n";
echo strftime(YearOfWeek($format)) . "\n";
?>
denis at spiralsolutions dot com
02-Nov-2006 12:07
(in addition to Andy's post)
To get a RFC 2822 date (used in RSS) of the current local time :
echo strftime ("%a, %d %b %Y %H:%M:%S %z") ;
Note: option %z / %Z - work different on Windows platform, for example
output of this code line can be:
Thu, 02 Nov 2006 09:54:59 Jerusalem Standard Time (on Windows)
Thu, 02 Nov 2006 09:54:59 +0200 (on Linux)
[red. It is much smarter to use date(DATE_RSS); here]
NicSoft
06-Oct-2006 12:02
Marian Sigler
Your point about javascript not being universal is correct. However, accept language header does not tell you the local time difference, which is the essential problem.
Also, as you point out, accept language is also not universal.
Most browsers do accept javascript. it is in common use by many websites. It is a safe bet if you are using drop down menus for instance that the script will work, otherwise they would not be able to use your site at all.
Marian Sigler
18-Sep-2006 11:45
@NicSoft: And what if the user's browser doesn't support JavaScript? You should either use the possibilities offered by PHP (most browsers send an Accept-Language header, from where you can extract the language to use) or at least offer the english name (e.g. inside <noscript>)
NicSoft
21-Aug-2006 04:05
A simple work around for displaying dates in local format is to get the browser to do it for you using javascript.
This routine accepts a date time field from sql,
and gets the timezone offset for your server, and passes these over to the browser in the form of a javascript script.
Javascript calculates the time difference and uses toLocaleString to display it.
function DisplaySQLDateInLocalTime($SQLDate){
list($year,$mon,$day,$hour,$min,$sec)=split('[-: ]',$SQLDate);
$TimeZoneOffset=date('Z') /60;
$JS="\n<script><!--\n";
$JS.="LocalTime = new Date();\n";
$JS.="TimeZoneOffsetInMins = LocalTime.getTimezoneOffset();\n";
$JS.="ServerTimeZoneOffset=$TimeZoneOffset;\n";
$JS.="timediff=-TimeZoneOffsetInMins - ServerTimeZoneOffset;\n";
$JS.="LocalTime = new Date(".$year.","
.($mon-1).",".$day.",".$hour.",".$min.",".$sec.");\n";
$JS.="DateVal=LocalTime.valueOf();\n";
$JS.="LocalTime=new Date(DateVal+timediff*1000*60);\n";
$JS.="document.write( LocalTime.toLocaleString());\n";
$JS.="//--></script>\n";
return $JS;
}
Moritz Stoltenburg
17-Aug-2006 08:45
In response to the note supplied by "Arpad Borsos":
I think the whole truth is that the output of strftime() considers whatever you stated with setlocale().
<?php
$locale = setlocale (LC_ALL, 'de_DE.UTF-8');
|
|