Главная | Руководство по MySQL | MySQL Manual | Документация к HTTP серверу Apache | Apache HTTP Server Documentation | downloads | faq

искать  Язык: Английский


date

(PHP 4, PHP 5)

dateФорматирует системную дату/время

Описание

string date ( string $format [, int $ timestamp ] )

Возвращает время, отформатированное в соответствии с аргументом format , используя метку времени, заданную аргументом timestamp или текущее системное время, если timestamp не задан. Другими словами, timestamp является необязательным и по умолчанию равен значению, возвращаемому функцией time().

Замечание: Для большинства систем допустимыми являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Эти даты соответствуют минимальному и максимальному значению 32-битового целого со знаком). Для Windows допустимы даты с 01-01-1970 по 19-01-2038.

Замечание: Для получения метки времени из строкового представления даты можно использовать функцию strtotime(). Кроме того, некоторые базы данных имеют собственные функции для преобразования внутреннего представления даты в метку времени (напрмер, функция MySQL » UNIX_TIMESTAMP).

В параметре format распознаются следующие символы
Символ в строке format Описание Пример возвращаемого значения
a Ante meridiem или Post meridiem в нижнем регистре am или pm
A Ante meridiem или Post meridiem в верхнем регистре AM или PM
B Время в стадарте Swatch Internet От 000 до 999
c Дата в формате ISO 8601 (добавлено в PHP 5) 2004-02-12T15:19:21+00:00
d День месяца, 2 цифры с ведущими нулями от 01 до 31
D Сокращенное наименование дня недели, 3 символа от Mon до Sun
F Полное наименование месяца, например January или March от January до December
g Часы в 12-часовом формате без ведущих нулей От 1 до 12
G Часы в 24-часовом формате без ведущих нулей От 0 до 23
h Часы в 12-часовом формате с ведущими нулями От 01 до 12
H Часы в 24-часовом формате с ведущими нулями От 00 до 23
i Минуты с ведущими нулями 00 to 59
I (заглавная i) Признак летнего времени 1, если дата соответствует летнему времени, иначе 0 otherwise.
j День месяца без ведущих нулей От 1 до 31
l (строчная 'L') Полное наименование дня недели От Sunday до Saturday
L Признак високосного года 1, если год високосный, иначе 0.
m Порядковый номер месяца с ведущими нулями От 01 до 12
M Сокращенное наименование месяца, 3 символа От Jan до Dec
n Порядковый номер месяца без ведущих нулей От 1 до 12
O Разница с временем по Гринвичу в часах Например: +0200
r Дата в формате » RFC 2822 Например: Thu, 21 Dec 2000 16:01:07 +0200
s Секунды с ведущими нулями От 00 до 59
S Английский суффикс порядкового числительного дня месяца, 2 символа st, nd, rd или th. Применяется совместно с j
t Количество дней в месяце От 28 до 31
T Временная зона на сервере Примеры: EST, MDT ...
U Количество секунд, прошедших с начала Эпохи Unix (The Unix Epoch, 1 января 1970, 00:00:00 GMT) См. также time()
w Порядковый номер дня недели От 0 (воскресенье) до 6 (суббота)
W Порядковый номер недели года по ISO-8601, первый день недели - понедельник (добавлено в PHP 4.1.0) Например: 42 (42-я неделя года)
Y Порядковый номер года, 4 цифры Примеры: 1999, 2003
y Номер года, 2 цифры Примеры: 99, 03
z Порядковый номер дня в году (нумерация с 0) От 0 до 365
Z Смещение временной зоны в секундах. Для временных зон западнее UTC это отрицательное число, восточнее UTC - положительное. От -43200 до 43200

Любые другие символы, встреченные в строке format , будут выведены в результирующую строку без изменений. Z всегда возвращает 0 при использовании gmdate().

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

<?php
// вывод дня недели, например Wednesday
echo date("l");

// вывод даты в формате: Wednesday 15th of January 2003 05:51:38 AM
echo date("l dS of F Y h:i:s A");

// вывод: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));
?>

Избежать распознавания символа как форматирующего можно, если экранировать этот символ с помощью \ Если в сочетании с \ символ являееся специальным (например, \t), следует добавлять еще один \.

Пример #2 Экранирование символов в функции date()

<?php
// вывод: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

Функции date() и mktime() для вывода прошедших и будущих дат.

Пример #3 date() и mktime() example

<?php
$tomorrow  
mktime(000date("m")  , date("d")+1date("Y"));
$lastmonth mktime(000date("m")-1date("d"),   date("Y"));
$nextyear  mktime(000date("m"),   date("d"),   date("Y")+1);
?>

Замечание: Этот метод более надежен, чем вычитание и прибавление секунд к метке времени, так как mktime() учитывает любые неоднозначности в датах (переход на летнее/зимнее время и др.).

Приведем еще несколько примеров использования функции date(). Помните, что следует экранировать все символы, которые вы хотите видеть в результате работы функции без изменений. Это относится и к символам, которые в текущей версии PHP не распознаются как специальные, так как этим символам может быть назначено значение в следующих версиях. Используйте одинарные кавычки для предотвращения преобразования \n в перевод строки.

Пример #4 Форматирование с использованием date()

<?php
// Предположим, что текущая дата March 10th, 2001, 5:16:18 pm

$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 z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$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 15:16:08 MST 2001
$today date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today date("H:i:s");                         // 17:16:17
?>

Для форматирования дат на других языках используйте функции setlocale() и strftime().

См. также описание функций getlastmod(), gmdate(), mktime(), strftime() и time().


User Contributed Notes
date
arturaz at gmail dot com
04-Jun-2010 09:37
To find difference in months this will help you:

<?php
function diff_in_months($start_date, $end_date, $additional_months=1)
{
   
$start_year = date("Y", strtotime($start_date));
   
$start_month = date("n", strtotime($start_date));
   
   
$end_year = date("Y", strtotime($end_date));
   
$end_month = date("n", strtotime($end_date));
   
   
$diff_in_months = ($end_year - $start_year) * 12 - $start_month + $end_month + $additional_months;
    return
$diff_in_months;   
}

// Usage
echo "Diff in months: " . diff_in_monhts("2008-07-05", "2009-03-14", 1);

?>
gaetan at exultet dot net
04-Jun-2010 02:04
I needed ton obtain date of the first day and the last day of a month. It's OK even for leap years.

Date de d�cbut et de fin du mois, même pour ann�ces bisextiles

<?Php
$year
=2008;
$month=2;
//
$begin=mktime(0,0,0,$month,1,$year);
$end=strtotime("+1month -1day",$begin);
echo
date('Y-m-d',$begin);    // 2008-02-01
echo ' - ';
echo
date('Y-m-d',$end);      // 2008-02-29
?>

Hope it helps someone
keyboard4444 at gmail dot com
28-Apr-2010 02:43
In report generation I use this to create list of week for the year (display all the week)

<?php
$zxc
= date('Y'); //Get the current year
$qwe = strtotime( "$zxc-1-1"); //First day of the Year

//1 year has 52 week
for( $week = 0; $week <= 52; $week++)
{
   
$asd = strtotime( "+$week week" ,$qwe);

   
$valid = $asd;
    echo
"Week ".date( 'W', $valid).", ".date( 'Y-m-d', $valid)."<br/>";
}
?>
fabiocbalbuquerque at gmail dot com
20-Apr-2010 05:05
I made this function so I can convert microtime (microseconds) into millitime (milliseconds). In this particular case, I have a function that when I give a valid Date, following or not by a pattern (like 'Y-m-d') and using the micro_to_millis intermediate function, it returns the given Date in milliseconds. By the other side, the date_from_millis function returns a valid and formatted date from a given milli number.

<?php
// simple way to avoid magic numbers
DEFINE(MILLI, 1000);
DEFINE(RPRECISION, 10);
DEFINE(DAY_SECONDS, 86400);

function
date_to_millis($date, $pattern='d.m.Y') {
       
$millisPerDay = DAY_SECONDS*MILLI;

        list(
$d, $m, $y) = explode($date, '.');
        return
micro_to_milli($d*$m*$y*$millisPerDay);
}

function
micro_to_milli($microDate=null) {
       
$date = ($date) ? $date : microtime();
        list (
$usec, $sec) = explode (' ', $date);
        return (float)
$sec*MILLI + round($usec/MILLI, RPRECISION);
}

function
date_from_millis($millis, $pattern='d.m.Y') {
       
$millis = ($millis) ? $millis : micro_to_milli();
       
// returns the date using the given pattern or 'd.m.y' by default
       
return date($pattern, $millis/MILLI);
}

// actual date
$date = date('d.m.Y');
var_dump($date);

// actual date in milliseconds
$milliFromDate = date_to_millis($date);
var_dump($milliFromDate);

// actual date back from millis
$dateFromMilli = date_from_millis($milli);
var_dump($dateFromMilli);
  
?>
robin at stylr dot nl
18-Apr-2010 06:50
This is a little function that returns only a working day (monday until friday). It's flexible due to the use of a 'forbidden days' array.
I used this in a project where the delivery date can only be 10 days from now and only on a working day (mo - fr).

<?php
function wdays($strTime = NULL){
   
$arrWeekend = array("6","7"); // saturday and sunday
   
$strTime = (is_null($strTime)) ? strtotime("+10 days") : $strTime;
    if(
in_array(date("N", $strTime), $arrWeekend)){
        return
wdays(strtotime("+1 day", $strTime));
    }
    else {
        return
$strTime;
    }
}

echo
date("d-m-Y",wdays());
?>
justinclark at mydesktophelp dot com
28-Jan-2010 06:47
I suppose we run an off week in which week one is considered to start on the Monday of the week that contains Jan 1.  All the date functions seemed to be incorrect for this week calculation so here's what I came up with to give me the week number we needed.  Ideally we aren't the only people in the world that uses that calculation:

So:
week_of_year("12", "27", "2009") is "52"
week_of_year("12", "28", "2009") is "1"
week_of_year("1", "4", "2010") is "2"

Id assume if you needed to start on another weekday you could modify it to look for that day instead of Mon.

<?php
function week_of_year($month, $day, $year) {
   
//Get date supplied Timestamp;
   
$thisdate = mktime(0,0,0,$month,$day,$year);
   
//If the 1st day of year is a monday then Day 1 is Jan 1
   
if (date("D", mktime(0,0,0,1,1,$year)) == "Mon"){
       
$day1=mktime (0,0,0,1,1,$year);
    } else {
       
//If date supplied is in last 4 days of last year then find the monday before Jan 1 of next year
       
if (date("z", mktime(0,0,0,$month,$day,$year)) >= "361"){
           
$day1=strtotime("last Monday", mktime(0,0,0,1,1,$year+1));
        } else {
           
$day1=strtotime("last Monday", mktime(0,0,0,1,1,$year));
        }
    }
   
// Calcualte how many days have passed since Day 1
   
$dayspassed=(($thisdate - $day1)/60/60/24);
   
//If Day is Sunday then count that day other wise look for the next sunday
   
if (date("D", mktime(0,0,0,$month,$day,$year))=="Sun"){
       
$sunday = mktime(0,0,0,$month,$day,$year);
    } else {
       
$sunday = strtotime("next Sunday", mktime(0,0,0,$month,$day,$year));   
    }
   
// Calculate how many more days until Sunday from date supplied
   
$daysleft = (($sunday - $thisdate)/60/60/24);
   
// Add how many days have passed since figured Day 1
    // plus how many days are left in the week until Sunday
    // plus 1 for today
    // and divide by 7 to get what week number it is
   
$thisweek = ($dayspassed + $daysleft+1)/7;
    return
$thisweek;
}
?>
robert at extremedesigns dot de
24-Jan-2010 11:26
if you wish to output a local time, instead of using date_default_timezone_get() and date_default_timezone_set() to manipulate your current timezone, simply create a new DateTime object:

<?php
$timezone
= new DateTimeZone( "Europe/London" );
$date = new DateTime();
$date->setTimezone( $timezone );
echo 
$date->format( 'H:i:s A  /  D, M jS, Y' );
?>

-> 22:59:34 PM / Sun, Jan 24th, 2010

Irrespective of current server location, this will output the local time in London, Europe.
No need to reset the server timezone back to the previous setting.
parweb at gmail dot com
20-Jan-2010 11:08
if you want to find the date start and end of the current semester
si vous voulez trouver la date de debut et de fin du semestre en cours

<?php

function ecartsemester( $date ) {
   
$date_time = strtotime( $date );

   
// dont ask me why 6.1 i dont know ;)
    // me demandez pas pourquoi 6.1, je sais pas ;)

   
$current_semester = (int)floor(date('m', strtotime($date)) / 6.1) + 1;
   
$debut_month = ( $current_semester - 1 ) * 6;
   
$debut_month++;

   
   
$date_start_time = mktime( 0, 0, 0, $debut_month, 1, date( 'Y', $date_time ) );
   
$date_start = date( 'Y-m-d 00:00:00', $date_start_time );
   
$date_end = date( 'Y-m-d 23:59:59', strtotime( '+6 month -1 day', $date_start_time ) );

    return array(
'date_start' => $date_start, 'date_end' => $date_end );
}

$ecartsemester1 = ecartsemester( '2010-01-20' );
$ecartsemester2 = ecartsemester( '2010-08-20' );

echo
'<pre>';
   
print_r( $ecartsemester1 );
   
print_r( $ecartsemester2 );
echo
'</pre>';exit;

and
the return
et le retour

Array
(
    [
date_start] => 2010-01-01 00:00:00
   
[date_end] => 2010-06-30 23:59:59
)
Array
(
    [
date_start] => 2010-07-01 00:00:00
   
[date_end] => 2010-12-31 23:59:59
)

?>
jm AT trinitywebdev DOT com
08-Jan-2010 06:52
Date Math should not be Hard ... I messed with this to get a consistant result for far to long... Here is a function that makes date math and format output relatively simple. I am sure with additional effort it could be made Time Aware and more compact but it works for most of what I need...enjoy

Function jmDateMath($SourceDate,$doMath,$ReturnFmt){
        /*
         * ~~ jm AT trinitywebdev DOT com ~~
         *
         * doMath Format[+/-][Qty][Unit]   
         *
         * Example +6m = Add 6 Months
         * Example -180d = Subtract 180 Days
         * Example +1Y = Add 1 Year
         *
         * Unit follows date() formats
         * @return newday
         */
        $SourceDate = strtotime($SourceDate);
        if(!$SourceDate){
            return(0);
        }
        if($ReturnFmt == ''){
            $ReturnFmt = 'm/d/Y';
        }
        $m = date('m',$SourceDate);
        $d = date('d',$SourceDate);
        $Y = date('Y',$SourceDate);
        $MathFunc = substr($doMath,0,1);
        $Unit = substr($doMath,-1,1);
        $Qty = substr($doMath, 1,strlen($doMath)-2);
        if($MathFunc == '-'){
            Switch($Unit){
                Case "m":
                    $newday = mktime(0,0,0,($m-$Qty),$d,$Y);
                break;
                Case "d":
                    $newday = mktime(0,0,0,$m,($d-$Qty),$Y);
                break;
                Case "Y":
                    $newday = mktime(0,0,0,$m,$d,($Y-$Qty));
                break;
            }
           
        }elseif($MathFunc == '+'){

            Switch($Unit){
                Case "m":
                    $newday = mktime(0,0,0,($m+$Qty),$d,$Y);
                break;
                Case "d":
                    $newday = mktime(0,0,0,$m,($d+$Qty),$Y);
                break;
                Case "Y":
                    $newday = mktime(0,0,0,$m,$d,($Y+$Qty));
                break;
            }
        }elseif($doMath ==''){
            $newday = mktime(0,0,0,$m,$d,$Y);
        }
       
        $newday = date($ReturnFmt,$newday);
        return($newday);
    }
vials_sha at yahoo dot com
18-Dec-2009 11:52
This function helps you to calculate exact years and months between two given dates $doj1 and $doj.. it returns example 4.3 means 4years and 3months
<?php
function cal_exp($doj1)
{
 
$doj1=strtotime($doj1);
 
$doj=date("m/d/Y",$doj1); //till date or any given date
 
  
$now=date("m/d/Y");
 
//$b=strtotime($b1);
  //echo $c=$b1-$a2;
//echo date("Y-m-d H:i:s",$c);
$year=date("Y");
//$chk_leap=is_leapyear($year);

//$year_diff=365.25;

$x=explode("/",$doj);
$y1=explode("/",$now);

$yy=$x[2];
$mm=$x[0];
$dd=$x[1];

$yy1=$y1[2];
$mm1=$y1[0];
$dd1=$y1[1];
$mn=0;
$mn1=0;
$ye=0;
if(
$mm1>$mm)
{
   
$mn=$mm1-$mm;
    if(
$dd1<$dd)
    {
   
$mn=$mn-1;
    }
   
    
$ye=$yy1-$yy;   
}
else if(
$mm1<$mm)
{
    
$mn=12-$mm;
   
//$mn=$mn;
   
   
if($mm!=1)
    {
    
$mn1=$mm1-1;
   
    }
   
    
$mn+=$mn1;
    if(
$dd1>$dd)
    {
    
$mn+=1;
    }
   
   
$yy=$yy+1;
   
$ye=$yy1-$yy;
    
}
else
{
   
$ye=$yy1-$yy;
   
$ye=$ye-1;
   
   
$mn=12-1;
   
    if(
$dd1>$dd)
    {
   
$ye+=1;
   
$mn=0;
    }
}

$to=$ye." year and ".$mn." months";
return
$ye.".".$mn;

/*return daysDiff($x[2],$x[0],$x[1]);
 $days=dateDiff("/",$now,$doj)/$year_diff;
$days_exp=explode(".",$days);
return $years_exp=$days; //number of years exp*/

   

   

}
?>
binupillai2003 at yahoo dot com,Binu dot V dot Pillai
17-Dec-2009 10:07
<?php
/*
Add day/week/month to a particular date
@param1 yyyy-mm-dd
@param1 integer
by Binu V Pillai on 2009-12-17
*/

function addDate($date,$day)//add days
{
$sum = strtotime(date("Y-m-d", strtotime("$date")) . " +$day days");
$dateTo=date('Y-m-d',$sum);
return
$dateTo;
}

?>
lb at bostontech dot net
30-Nov-2009 07:11
Not sure why this got ignored the first time, but this is an even simpler way to check leap year:

<?php
function isLeapYear($year)
    { return (((
$year%4==0) && ($year%100)) || $year%400==0) ? (true):(false); }
?>
andrea at bhweb dot it
28-Nov-2009 03:02
I created two functions useful to those that need to work with MySQL's YEARWEEK.

<?php
/**
 * Gives a YEARWEEK compatible with MySQL's YEARWEEK('date', 3)
 *
 * @param int|null $date the timestamp or null = now
 * @return string YEARWEEK
 * @author Andrea Baron <andrea@bhweb.it>
 */
function yearweek($date = null) {
    if(
$date === null)
       
$date = time();
   
    return
sprintf('%04d%02d', date('o', $date), date('W', $date));
}

/**
 * Gives starting day (monday) and ending day (sunday) of the given
 * YEARWEEK
 *
 * @param int|string $yw the YEARWEEK
 * @return array on index 0 the start, on index 1 the end
 * @author Andrea Baron <andrea@bhweb.it>
 */
function yearweekToLimits($yw) {
   
$jan1st = mktime(0, 0, 0, 1, 1, floor($yw / 100));
   
$sw = $yw % 100 - 2;
   
$ew = $sw + 1;
   
$dow = idate('w', $jan1st);
    if(
$dow >= 5 || $dow <= 0) {
        ++
$sw;
        ++
$ew;
    }
    elseif(
$dow === 1)
        ++
$sw;
    if(
$sw >= 0)
       
$sw = '+'.$sw;
    if(
$ew >= 0)
       
$ew = '+'.$ew;
    return array(
       
strtotime($sw.' week mon', $jan1st),
       
strtotime($ew.' week sun', $jan1st),
    );
}
?>
mohan6678 gmail.com
24-Nov-2009 05:40
There is a date Y 0000 bug in power pc machines, which was fixed in [5.2.10] (I think). But I still a bit old php version.

I wrote this workaround using APD override_function

It uses linux date command.

<?php
  override_function
('date', '$format,$timestamp=0', 'return dateFix($format,$timestamp);');
   
    function
dateFix($format,$timestamp)
    {
        if(
$timestamp == 0)
        {
           
$timestamp = time();
        }
       
$date = exec("php -r 'echo date($format,$timestamp);'");
       
$year = exec('date +"%Y"');
        return
str_replace('0000',$year,$date);
    }
?>

Feel free to use it.
superpck at yahoo dot com
08-Nov-2009 05:53
Find whether the leap year or not with simple function, check by the last day in February is 29 or not.

<?php
function IsLeapYear($Year)
{
   
$Year = ($Year >= 2300)? ($Year-543):$Year ;        // if check by B.E year (Buddhist era)
   
return (date("d",mktime(0,0,0,3,0,$Year)) == 29)? TRUE:FALSE;
}
?>
zedar
01-Nov-2009 12:54
This Function returns the date berfore X days.

you call this function ""daybefore(X)""  X days

<?php
function daybefore($j){
$day = date('d');
$month = date('m');
$year = date('Y');
for (
$i=0; $i<$j; $i++) {
if (
$day==1) {
    if (
$month == 1) {
       
$day = 31;
       
$month = 12;
       
$year = $year - 1;
    } else {
       
$month = $month - 1;
        switch (
$month) {
            case
01:
               
$maxdays=31;
                break;
            case
02:
               
$a = $year / 4;
               
$b = ceil($a);
                if (
$a==$b){               
                    
$maxdays=29;
                } else {
                     
$maxdays=28;
                }
                break;
            case
03:
               
$maxdays=31;
                break;
            case
04:
               
$maxdays=30;
                break;
            case
05:
               
$maxdays=31;
                break;
            case
06:
               
$maxdays=30;
                break;
            case
07:
               
$maxdays=31;
                break;
            case
08:
               
$maxdays=31;
                break;
            case
09:
               
$maxdays=30;
                break;
            case
10:
               
$maxdays=31;
                break;
            case
11:
               
$maxdays=30;
                break;
            case
12:
               
$maxdays=31;
                break;
        }
       
$day = $maxdays;
       
$year = $year;
    }
} else {
   
$day = $day - 1;
   
$month = $month;
   
$year = $year;
}}
return
"$year-$month-$day";
}
echo
daybefore(3);
?>
dev at omikrosys dot com
15-Oct-2009 06:14
1. Find whether an year is a leap year or not.
2. Find the number of days in a given month of a year.

<?php
function leapYear($year){
 if (
$year % 400 == 0 || ($year % 4 == 0 && $year % 100 != 0)) return TRUE;
 return
FALSE;
}
function
daysInMonth($month = 0, $year = ''){
 
$days_in_month    = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 
$d = array("Jan" => 31, "Feb" => 28, "Mar" => 31, "Apr" => 30, "May" => 31, "Jun" => 30, "Jul" => 31, "Aug" => 31, "Sept" => 30, "Oct" => 31, "Nov" => 30, "Dec" => 31);
 if(!
is_numeric($year) || strlen($year) != 4) $year = date('Y');
 if(
$month == 2 || $month == 'Feb'){
  if(
leapYear($year)) return 29;
 }
 if(
is_numeric($month)){
  if(
$month < 1 || $month > 12) return 0;
  else return
$days_in_month[$month - 1];
 }
 else{
  if(
in_array($month, array_keys($d))) return $d[$month];
  else return
0;
 }
}
?>

You can call the function as <?php daysInMonth(02, 2008); ?> or <?php daysInMonth('Feb', 2008); ?>
If no year is specified then the current year will be used/shown.
d basin
14-Oct-2009 10:35
convert an "excel" formatted date. Example:

<?php

$excel_date
= 40179;

$normal_date = date("m/d/Y", strtotime("01/01/1900 + $excel_date days - 2 days"));

echo(
$normal_date);

?>

result: "01/01/2010"
omikrosys at gmail dot com
13-Oct-2009 11:40
Date Validation Code

<?php
function validDate($date){
 
//replace / with - in the date
 
$date = strtr($date,'/','-');
 
//explode the date into date,month and year
 
$datearr = explode('-', $date);
 
//count that there are 3 elements in the array
 
if(count($datearr) == 3){
  list(
$d, $m, $y) = $datearr;
 
/*checkdate - check whether the date is valid. strtotime - Parse about any English textual datetime description into a Unix timestamp. Thus, it restricts any input before 1901 and after 2038, i.e., it invalidate outrange dates like 01-01-2500. preg_match - match the pattern*/
 
if(checkdate($m, $d, $y) && strtotime("$y-$m-$d") && preg_match('#\b\d{2}[/-]\d{2}[/-]\d{4}\b#', "$d-$m-$y"))
   {
/*echo "valid date";*/ return TRUE;}
  else {
/*echo "invalid date";*/ return FALSE;}
  }
  else {
/*echo "invalid date";*/ return FALSE;}
 
/*echo "invalid date";*/ return FALSE;
 }
?>
Marcin Szychowski
08-Oct-2009 01:59
MS-DOS related filesystems, along with ZIP files, store date and time in four bytes (time: 2 bytes, date: 2 bytes), as described in Wikipedia: http://en.wikipedia.org/wiki/File_Allocation_Table#Directory_table

As it took me some time to not-find any functions to convert unix to ms-dos timestamps, I decided to put these simple functions here, to save somebody else's time:

<?php

// $ts - standard UNIX timestamp, as returned by mktime()
function packTimeDate($ts){
   
// MS-DOS can store dates ranging from 1980-01-01 up to 2107-12-31
   
$year=date('Y', $ts);
    if((
$year<1980) || ($year>2107)) return "\x00\x00";
    else return
packTime($ts).packDate($ts);
}

/** From Wikipedia:
 * 15-11 Hours (0-23)
 * 10-5  Minutes (0-59)
 *  4-0  Seconds/2 (0-29)
 **/
function packTime($ts){
   
$sec=round((('1'.date('s', $ts))-100)/2);
   
$min=('1'.date('i', $ts))-100;
   
$hour=date('G', $ts);

   
$dosTime=($hour<<11)+($min<<5)+$sec;

   
$m[0]=$dosTime%256;
   
$m[1]=(($dosTime-$m[0])/256)%256;
    return
sprintf('%c%c', $m[0], $m[1]);
}

/** From Wikipedia:
 * 15-9 Year (0 = 1980, 127 = 2107)
 *  8-5 Month (1 = January, 12 = December)
 *  4-0 Day (1 - 31)
 **/
function packDate($ts){
   
$year=date('Y', $ts)-1980;
   
$day=date('j', $ts);
   
$month=date('n', $ts);

   
$dosDate=($year<<9)+($month<<5)+$day;

   
$m[0]=$dosDate%256;
   
$m[1]=(($dosDate-$m[0])/256)%256;
    return
sprintf('%c%c', $m[0], $m[1]);
}

?>

As I didn't need to unpackTimeDate, I didn't bother to write reverse functions. Feel free to provide yours if You care.

Have fun with PHP!
Edward Rudd
05-Oct-2009 07:13
To actually make use ot the "u" (microsecond) you need to use the DateTime object and not the date() function.

For example

<?php
$t
= microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );

print
$d->format("Y-m-d H:i:s.u");
?>
void at informance dot info
25-Sep-2009 08:14
The microseconds indicator ('u') seems not to be usable under Windows :

<?php echo date('s u') ?>

will return for example

57 000000

It is probably due to Windows not handling natively microseconds.
Sean Proctor
02-Sep-2009 06:22
For the week number for weeks starting on Sunday:

<?php
function week_of_year($month, $day, $year) {

$day_of_year = date('z', mktime(0, 0, 0, $month, $day, $year));

/* Days in the week before Jan 1. If you want weeks to start on Monday make this (x + 6) % 7 */
$days_before_year = date('w', mktime(0, 0, 0, 1, 1, $year));

$days_left_in_week = 7 - date('w', mktime(0, 0, 0, $month, $day, $year));

/* find the number of weeks by adding the days in the week before the start of the year, days up to $day, and the days left in this week, then divide by 7 */
return ($days_before_year + $day_of_year + $days_left_in_week) / 7;

}
?>
critic at hot dot ee
30-Aug-2009 08:36
If u want to get weekday date -
30.08.2009 weekdays are 24-30
i want to get 5-th day of that week - 28.08.2009

<?PHP

function week_day($month, $year, $current_day, $week_day_number=1){

   
$loop_start = $current_day-(date('N', mktime(0, 0, 0, $month, $current_day, $year))-1);//lets start loop from first day of week
   
$loop_end = $current_day+(7-(date('N', mktime(0, 0, 0, $month, $current_day, $year))));//lets end loop to last day of week

   
for($i = $loop_start; $i<=$loop_end; $i++){

       
$day_of_the_week = date('N', mktime(0, 0, 0, $month, $i, $year));//current day number 1-7 of week
       
$loop_date = date('d', mktime(0, 0, 0, $month, $i, $year));//current day in calendar
       
if($day_of_the_week == $week_day_number){//if weekday number equals day number then lets return date

           
return $loop_date;
        }
    }
}

echo
week_day(8, 2009, 30, 1);//returns (24).08.2009
echo '<br>';
echo
week_day(8, 2009, 30, 5);//returns (28).08.2009

?>
czerpmac [at] gmail [dot] com
29-Aug-2009 06:02
Easy way to numeric representation of a quarter from passed as parametr date.

<?php
/**
 * quarterByDate()
 *
 * Return numeric representation of a quarter from passed free-form date.
 *
 * @param mixed $date
 * @return integer
 */
function quarterByDate($date)
{
    return (int)
floor(date('m', strtotime($date)) / 3.1) + 1;
}
?>

Example:

<?php
$quarter
= quarterByDate(date('Y-m-d'));    // current quarter. For 2009-08-29 will be "3"
$quarter = quarterByDate('2009-12');        // will be "4"
$quarter = quarterByDate('March');        // will be "1"
?>

I hope it will be useful.

Best regards,
S_P_E_C
kenaniah at gmail dot com
25-Aug-2009 11:31
This function behaves like date, but allows you to output the date in a given time zone locale.

<?php
function date_at_timezone($format, $locale, $timestamp=null){
   
    if(
is_null($timestamp)) $timestamp = time();
   
   
//Prepare to calculate the time zone offset
   
$current = time();
   
   
//Switch to new time zone locale
   
$tz = date_default_timezone_get();
   
date_default_timezone_set($locale);
   
   
//Calculate the offset
   
$offset = time() - $current;
   
   
//Get the date in the new locale
   
$output = date($format, $timestamp - $offset);
   
   
//Restore the previous time zone
   
date_default_timezone_set($tz);
   
    return
$output;
   
}

//Examples
$t = time();

print
date("g:i A T", $t); //4:16 PM PDT
print date_at_timezone("g:i A T", "America/New_York", $t); //7:16 PM EDT
print date_at_timezone("g:i A T", "Pacific/Samoa", $t); //12:16 PM SST
print date("g:i A T", $t); //4:16 PM PDT
?>
Aura@The World
24-Aug-2009 10:04
Get names of days:

<?php
$tz
= date_default_timezone_get();
date_default_timezone_set('UTC');
for(
$i=0; $i<7; $i++)
   echo
date('D', mktime(12, 0, 0, 1, $i+4, 1970)) . '<br />';
date_default_timezone_set($tz);
?>

Change 'D' to 'l' (lowercase 'L') for full names. Change $i+4 to $i+5 if you want Monday to be the first day of the week.
christophermmann at gmail dot com
19-Aug-2009 11:44
I couldn't find a function to do this properly. All functions I could find would use the current month as an argument.

Anyway, this function will find the occurence of a particular weekday in a particular month. For instance, the second wednesday in june 2009 would be called by:

<?php
echo findFirstDayofWeek(6,2009, "Wednesday", 2);
?>

Where 6 is "June", 2009 is the year, Wednesday is the weekday we want and 2 is the 2nd occurence.

<?php

function findFirstDayOfWeek($month, $year, $day, $offset){ // supply the month, year, day and offset
   
$FirstDay = mktime(0, 0, 0, $month, 1, $year); // Get the first day of the month in question
   
$DayName = date("l", $FirstDay); //set the name of the first day for the while loop
   
$CurrentStamp = $FirstDay; // set a disposable variable for use in the while loop
   
$Results = 0; //set the number of results (for use with the offset argument)
   
While($Results != $offset){ //while the number of results does not equal the offset we are looking for
       
$CurrentStamp = $CurrentStamp + 86400; // add a day
       
if(date("l", $CurrentStamp) == $day){ // if the name of the weekday we are currently looping at is the same name as the argument supplied, set the date variable to that weekday and increment the results variable by 1
           
$Date = date("Y-m-d", $CurrentStamp);
           
$Results++;
        }
    }
    if(
date("n", $CurrentStamp) != $month){ // this line checks whether or not the date that the while loop has found is in the same month we are asking form otherwise, there must be no "3rd friday in august"
   
return "No weekday at this offset";
    } else {
    return
$Date; //send back the date
   
}
}

echo
findFirstDayofWeek(9,2009, "Friday", 5); // returns a formatted date for the first instance of a certain day in the argumental month
?>
crayonviolent at phpfreaks dot com
29-Jul-2009 12:25
Haven't really tested it performance-wise vs. other methods, but I thought I'd post this anyways...

Here's a nifty way to exploit date()'s built-in ordinal suffix calculator to append the proper ordinal suffix to an arbitrary number:

<?php
function addOrdinal($num=0){
  return
$num.(((strlen($num)>1)&&(substr($num,-2,1)=='1'))?
        
'th' : date("S",mktime(0,0,0,0,substr($num,-1),0)));
}
// end function addOrdinal
?>
Just.Kevin
28-Jul-2009 04:52
In order to determine if a year is a leap year an earlier poster suggested simply checking to see if the year is a multiple of four:

<?php
function is_leapyear_broken($year = 2004) {
return (
$year%4)==0;
}
?>

While this will work for the majority of years it will not work on years that are multiples of 100 but not multiples of 400 i.e.(2100).
A function not using php's date() function that will also account for this small anomaly in leap years:

<?php
function is_leapyear_working($year = 2004) {
    if(((
$year%4==0) && ($year%100!=0)) || $year%400==0) {
        return
true;
    }
    return
false;
}
?>

While is_leapyear_working will not return true for the few non-leap years divisible by four I couldn't tell you if this is more or less efficient than using php's date() as an even earlier poster suggested:

<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return
$is_leap;
}
?>
get.mango at gmail.com (Mangesh Sangapu)
28-Jul-2009 04:31
(Referring to the leap year posts)

Not every year that is divisible by 4 is a leap year. There are other conditions. Here's the complete list:

   1. Every year that is evenly divisible by four is a leap year;
   2. of those years, if it can be evenly divided by 100, it is NOT a leap year, unless
   3. the year is evenly divisible by 400. Then it is a leap year.

<?php
function is_leapyear($year) {

if ( (
$year%4) != 0 )
{     return
false;     }

if ( (
$year%100)==0 )
{
     if ( (
$year%400) == 0 )
     {     return
true;     }
     else
     {     return
false;    }
}
else
{     return
true;     }

}
?>
seanj
24-Jul-2009 02:58
An earlier user posted a script to detect whether or not a given year is a leap year:

<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return
$is_leap;
}
?>

You're thinking too hard! Just check to see if the year is a multiple of four:

<?php
function is_leapyear($year = 2004) {
return (
$year%4)==0;
}
?>

or better yet, just use that single line in your code.
ddd888 at mail333 dot com
08-Jul-2009 10:56
Slightly modified earlier written function for formatting date in russian.

<?php
/*
  these are the russian additional format characters
  �_: full textual representation of the day of the week
  �": full textual representation of the day of the week (first character is uppercase),
  к: short textual representation of the day of the week,
  �_: short textual representation of the day of the week (first character is uppercase),
  �_: full textual representation of a month
  �_: full textual representation of a month (first character is uppercase),
  �>: short textual representation of a month
  �>: short textual representation of a month (first character is uppercase),
*/
function date_ru($formatum, $timestamp=0) {
  if ((
$timestamp <= -1) || !is_numeric($timestamp)) return '';
 
$q['�_'] = array(-1 => 'w', '�_�_�_к�_���_���_�_��','п�_�_���_���>�_�_ик', '�_�'�_�_�_ик', '�_�_���_а', '�+���'�_���_�_', 'п�_�'�_и�+а', '�_�_�+�+�_�'а');
 
$q['�"'] = array(-1 => 'w', '�'�_�_к�_���_���_�_��','�_�_�_���_���>�_�_ик', '�'�'�_�_�_ик', 'С�_���_а', '����'�_���_�_', '�_�_�'�_и�+а', 'С�_�+�+�_�'а');
 
$q['к'] = array(-1 => 'w', '�_�_','п�_', '�_�'', '�_�_', '�+�'', 'п�'', '�_�+');
 
$q['�_'] = array(-1 => 'w' '�'�_','�_�_', '�'�'', '�_', '��'', '�_�'', '�+');
 
$q['�_'] = array(-1 => 'n', '', '�_�_�_а�_�_', '�"���_�_а�>�_', '�_а�_�'а', 'ап�_���>�_', '�_а�_', 'и�_�_�_', 'и�_�>�_', 'а�_�_�_�_�'а', '�_���_�'�_�+�_�_', '�_к�'�_�+�_�_', '�_�_�_�+�_�_', '�_��ка�+�_�_');
 
$q['�_'] = array(-1 => 'n', '', 'Я�_�_а�_�_', 'Ф���_�_а�>�_', '�_а�_�'', '�_п�_���>�_', '�_ай', '�_�_�_�_', '�_�_�>�_', '�_�_�_�_�_�'', 'С���_�'�_�+�_�_', '�_к�'�_�+�_�_', '�_�_�_�+�_�_', '�"��ка�+�_�_');
 
$q['�>'] = array(-1 => 'n', '', '�_�_�_', '�"���_', '�_а�_', 'ап�_', '�_ай', 'и�_�_', 'и�_�>', 'а�_�_', '�_���_', '�_к�'', '�_�_�_', '�_��к');
 
$q['�>'] = array(-1 => 'n', '' 'Я�_�_', 'Ф���_', '�_а�_', '�_п�_', '�_ай', '�_�_�_', '�_�_�>', '�_�_�_', 'С���_', '�_к�'', '�_�_�_', '�"��к');

  if (
$timestamp == 0)
   
$timestamp = time();
 
$temp = '';
 
$i = 0;
  while ( (
strpos($formatum, '�_', $i) !== FALSE) || (strpos($formatum, '�"', $i) !== FALSE) ||
          (
strpos($formatum, 'к', $i) !== FALSE) || (strpos($formatum, '�_', $i) !== FALSE) ||
          (
strpos($formatum, '�_', $i) !== FALSE) || (strpos($formatum, '�_', $i) !== FALSE) ||
          (
strpos($formatum, '�>', $i) !== FALSE) || (strpos($formatum, '�>', $i) !== FALSE)) {
   
$ch['�_']=strpos($formatum, '�_', $i);
   
$ch['�"']=strpos($formatum, '�"', $i);
   
$ch['к']=strpos($formatum, 'к', $i);
   
$ch['�_']=strpos($formatum, '�_', $i);
   
$ch['�_']=strpos($formatum, '�_', $i);
   
$ch['�_']=strpos($formatum, '�_', $i);
   
$ch['�>']=strpos($formatum, '�>', $i);
   
$ch['�>']=strpos($formatum, '�>', $i);
    foreach (
$ch as $k=>$v)
      if (
$v === FALSE)
        unset(
$ch[$k]);
   
$a = min($ch);
   
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
   
$i = $a+1;
  }
 
$temp .= date(substr($formatum, $i), $timestamp);
  return
$temp;
}

echo
'���_�_�_�_�_ '.date_ru('�", d �> Y');
?>
martinjsteven at gmail dot com
11-Jun-2009 11:20
A quick note about DATE_RSS and daylight savings...

DATE_RSS will return the timezone that your server is in as part of the format, which is normally correct when formatting a date for an RSS feed (RFC-822). 

However, if you're in the UK and it's the summer, your timezone is set as "BST".  This is not actually a valid RFC-822 timezone, thereby rendering DATE_RSS a bit useless for six months of the year. 

The valid extension would actually be GMT.  You should therefore adjust the time back by 1 hour and substitute the BST for GMT.
rez dot eza at gmail dot com
27-May-2009 04:12
<?php
//for Indonesian get return today

echo returnDate(date("N"), "day") . ", " . date("j") . " " . returnDate(date("n"), "month") . " " . date("Y");
   
    function
returnDate($num, $tipe){
       
$str;
        switch(
$tipe){
            case
"month":
               
$month_name = array("", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
               
$str = $month_name[floor($num)];
                break;
            case
"day":
               
$day_name = array("", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu");
               
$str = $day_name[floor($num)];
                break;
        }
       
        return
$str;
    }
?>
sarmad dot saadi at gmail dot com
24-May-2009 08:52
// showing how to detect a leap year
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return
$is_leap;
}
?>

<?php
$answer
= is_leapyear(2000);
if(
$answer) {

echo
"2000 is a leap year<BR>";
} else {
echo
"2000 is not a leap year.<BR>";
}
/* Use default for the parameter */
$yy="2003";
$answer = is_leapyear(2003);
if(
$answer) {

echo
"$yy is a leap year.<BR>";
} else {
echo
"$yy is not a leap year.<BR>";
}
?>
guido dot orellana at gmail dot com
29-Apr-2009 06:55
Function to obtain last week timestamps.

<?php

function LastWeek(){
   
$week = date('W');
   
$year = date('Y');
   
   
$lastweek=$week-1;
   
    if (
$lastweek==0){
       
$week = 52;
       
$year--;
    }
   
   
$lastweek=sprintf("%02d", $lastweek);
    for (
$i=1;$i<=7;$i++){
       
$arrdays[] = strtotime("$year". "W$lastweek"."$i");
    }
    return
$arrdays;
}

$days = LastWeek();
echo
"last week between " . date('Ymd000000',$days[0]) . " and " date('Ymd235959', $days[6]) . "\n";
?>
eduardo at digmotor dot com dot br
21-Apr-2009 08:34
Thanks to tcasparr at gmail dot com for the great idea (at least for me) ;)
I changed the code a little to replicate the functionality of date_parse_from_format, once I don't have PHP 5.3.0 yet. This might be useful for someone. Hope you don't mind changing your code tcasparr at gmail dot com.

<?php
/*******************************************************
 * Simple function to take in a date format and return array of associated
 * formats for each date element
 *
 * @return array
 * @param string $strFormat
 *
 * Example: Y/m/d g:i:s becomes
 * Array
 * (
 *     [year] => Y
 *     [month] => m
 *     [day] => d
 *     [hour] => g
 *     [minute] => i
 *     [second] => s
 * )
 *
 *  This function is needed for  PHP < 5.3.0
 ********************************************************/
function dateParseFromFormat($stFormat, $stData)
{
   
$aDataRet = array();
   
$aPieces = split('[:/.\ \-]', $stFormat);
   
$aDatePart = split('[:/.\ \-]', $stData);
    foreach(
$aPieces as $key=>$chPiece)   
    {
        switch (
$chPiece)
        {
            case
'd':
            case
'j':
               
$aDataRet['day'] = $aDatePart[$key];
                break;
               
            case
'F':
            case
'M':
            case
'm':
            case
'n':
               
$aDataRet['month'] = $aDatePart[$key];
                break;
               
            case
'o':
            case
'Y':
            case
'y':
               
$aDataRet['year'] = $aDatePart[$key];
                break;
           
            case
'g':
            case
'G':
            case
'h':
            case
'H':
               
$aDataRet['hour'] = $aDatePart[$key];
                break;   
               
            case
'i':
               
$aDataRet['minute'] = $aDatePart[$key];
                break;
               
            case
's':
               
$aDataRet['second'] = $aDatePart[$key];
                break;           
        }
       
    }
    return
$aDataRet;
}
?>

Also, if you need to change the format of dates:

<?php
function changeDateFormat($stDate,$stFormatFrom,$stFormatTo)
{
 
// When PHP 5.3.0 becomes available to me
  //$date = date_parse_from_format($stFormatFrom,$stDate);
  //For now I use the function above
 
$date = dateParseFromFormat($stFormatFrom,$stDate);
  return
date($stFormatTo,mktime($date['hour'],
                                   
$date['minute'],
                                   
$date['second'],
                                   
$date['month'],
                                   
$date['day'],
                                   
$date['year']));
}

?>
Anonymous
14-Apr-2009 02:10
Heads up: The date('W') week number of the year is computed based on Monday, and may not be exactly what you expect.  What is "Week 01" of year 2008?  This is different from the date('z') day number of the year which is computed from January 1 == day zero.

<?php // RAY_date_W.php
echo "<br/>" . date('W', strtotime("December 28, 2008")); // 52
echo "<br/>" . date('W', strtotime("December 29, 2008")); // 01
echo "<br/>" . date('W', strtotime("January   2, 2009")); // 01
if (!date('z', strtotime("January 1"))) echo "<br/>FALSE"; // FALSE
?>
tcasparr at gmail dot com
13-Apr-2009 05:21
<?php
/**
 * Simple function to take in a date format and return array of associated formats for each date element
 * @return array
 * @param string $strFormat
 *
 * Example: Y/m/d g:i:s becomes
 * Array
 * (
 *     [year] => Y
 *     [month] => m
 *     [day] => d
 *     [hour] => g
 *     [minute] => i
 *     [second] => s
 * )
 */
function extract_date_format($strFormat)
{
   
$format_array = array();
   
$pieces = split('[:/.\ \-]', $strFormat);
    foreach(
$pieces as $piece)   
    {
        switch (
$piece)
        {
            case
'd':
            case
'j':
               
$format_array['day'] = $piece;
                break;
               
            case
'F':
            case
'M':
            case
'm':
            case
'n':
               
$format_array['month'] = $piece;
                break;
               
            case
'o':
            case
'Y':
            case
'y':
               
$format_array['year'] = $piece;
                break;
           
            case
'g':
            case
'G':
            case
'h':
            case
'H':
               
$format_array['hour'] = $piece;
                break;   
               
            case
'i':
               
$format_array['minute'] = $piece;
                break;
               
            case
's':
               
$format_array['second'] = $piece;
                break;           
        }
       
    }
    return
$format_array;
}
?>
pierre
24-Feb-2009 10:22
It seems to me that you can reliably get the week range of a certain numeric week like so:

<?php

// 2009 is the year
// W01 is week number 1
// 1 is the day number (Monday), 7 would be Sunday
strtotime("2009W011");

// Example 1 (These return the days for Week 1 or 2009
Mon_timestamp = strtotime("2009W011");
Tue_timestamp = strtotime("2009W012");
Wed_timestamp = strtotime("2009W013");
Thu_timestamp = strtotime("2009W014");
Fri_timestamp = strtotime("2009W015");
Sat_timestamp = strtotime("2009W016");
Sun_timestamp = strtotime("2009W017");

// Example 2 (more dynamic)
// set the 7 dates of the week
for($i=1; $i<=7; $i++) {
   
$dates[$i] = strtotime($year.'W'.$week.$i);
}

?>

Just remember you must pad the week number if it's under 10. 1 won't work, it should be 01.
uramihsayibok, gmail, com
21-Jan-2009 02:47
In a refreshing change, this code snippet is *not* about calculating date differences or anything like that.

<background-story>
I've always preferred date() over strftime() because of what each offers. For example, date has an st/nd/rd for the day number (S) while strftime does not. It also has an unpadded day number (j) that strftime doesn't (%e pads it with a space).
On the other hand, each character in the format string for date() is translated unless you prepend a backslash...

Recently I've wanted to create links with date information in it. Like with "January 21st 2009" each part would be a link (January => /2009/01, 21st => /2009/01/21, 2009 => /2009). date() makes this difficult because the HTML markup gets the treatment as well as the Y/m/d characters. Escaping all of those is ugly, not to mention annoying.
</background-story>

Here's my combination of date's placeholders and strftime's % markers. It's the best solution I could think of (at 5am mind you) but I'm open to suggestions.
Lots of comments because the code is rather tricky.

<?php

/**
 * Combines placeholders from date() with the % marker from strftime()
 *
 * Like strftime, use %% for a literal %.
 *
 * @see date, strftime
 * @param string $format The format of the outputted date string
 * @param int $timestamp An integer Unix timestamp that defaults to the current local time
 * @return A formatted date string
 */
function strfdate($format, $timestamp = null) {
   
// look for tokens
   
if (preg_match_all('/(?<!%)(%%)*%(.)/', $format, $matches)) {
       
// passing false or null as the timestamp doesn't work so we
        // have to generate the default ourselves
       
if ($timestamp === null) $timestamp = time();
       
// run each token through date - all at once
        // combines them into a "a!b!c!d" list, runs it through date,
        // and splits it apart again
       
$parts = explode("!", date(implode("!", $matches[2]), $timestamp));
       
// (! should never show up in date() output so this works)

        // a second function is used sequentially:
        // the Xth time this function is called it will replace the Xth token
        // with the corresponding element in $parts (which is passed through as $a)
        //
        // @param array $a Meant to be $parts as defined above
        // @return $a[X] where X is how many times this function has been called
       
$replace = create_function('$a', 'static $i = 0; return $a[$i++];');
       
       
// find each token and get the replacement data from the $replace function
        // note how the text being replaced isn't used anywhere: we already know
        // what it is as it was used to create the $parts array
       
$result = preg_replace('/(%*)%./e', '"$1" . $replace($parts)', $format);
       
// finally "unescape" any %s
       
$result = str_replace("%%", "%", $result);
       
        return
$result;
    }
    return
$format;
}

?>
mrkrackham
18-Nov-2008 07:33
Just in case anyone else is looking for an easy-to-find equivalent for W3C Datetime or date("c") in a previous version of php, here's one I did.  Hope it helps someone.

<?php
function w3cDate($time=NULL)
{
    if (empty(
$time))
       
$time = time();
   
$offset = date("O",$time);
    return
date("Y-m-d\TH:i:s",$time).substr($offset,0,3).":".substr($offset,-2);
}
?>

Examples:
echo w3cDate(); //2008-11-18T12:15:18-07:00
echo w3cDate(mktime(2,3,4,5,6,2007)); //2007-05-06T02:03:04-06:00
sourabhshankar AT gmail DOT com
14-Nov-2008 08:43
<?php
/*
Find out start and end date of current week.
I am assuming that week starts at sunday and ends at saturday.
so a typical week will look like this: sun,mon,tue,wed,thu,fri,sat
if you find any bug/error, please email me.
*/

//sunday = start of week
$sat = 6; //saturday = end of week
$current_day=date('w');
$days_remaining_until_sat = $sat - $current_day;

$ts_start = strtotime("-$current_day days");
$ts_end = strtotime("+$days_remaining_until_sat days");

echo
date('m-d-Y',$ts_start); //start date
echo '<br>';
echo
date('m-d-Y',$ts_end); //end date

/*
OUTPUT (m-d-y):
11-09-2008
11-15-2008
*/
?>
Kenneth Kin Lum
02-Oct-2008 10:52
date(DATE_RFC822) and date(DATE_RFC2822) both work.  note that RFC 822 is obsoleted by RFC 2822.  The main difference is the year being 08 in RFC 822 and is 2008 in RFC 2822.

To use date(DATE_RFC2822), a short form is date('r').
Anonymous
12-Sep-2008 01:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
Cortexd
27-Aug-2008 06:47
a date function supporting the milliseconds format character

<?php
function udate($format, $utimestamp = null)
{
    if (
is_null($utimestamp))
       
$utimestamp = microtime(true);

   
$timestamp = floor($utimestamp);
   
$milliseconds = round(($utimestamp - $timestamp) * 1000000);

    return
date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}

echo
udate('H:i:s.u'); // 19:40:56.78128
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.45460
?>
pdubbb1 at gmail dot com
26-Aug-2008 12:32
here is the simpliest way to get the start and end date of the week;

<?php
$sdate
=date('c',strtotime(date('Y')."W".date('W')."0"));

$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>

the format is for the string in strtotime is;
 
     2008W200

this stands for year - 2008, constant never changes - W, week number of the year - 20, day of the week - 0 for sunday, 1 for monday, etc....

so 2008W200 stands for the sunday of the 20th week of 2008. 

This will only work in php 5 or better
abazaba.ru
14-Aug-2008 10:53
All novices must be very carefull when working with timestamps as second values.
From first glance it looks like date("Y-m-d H:i:s",TIMESTAMP) will return correct date, based on "how much seconds gone from 1970".
But here is the feature, it'll be corrected time, according to LOCAL timezone.

So if you take a 25200 as timestamp (10 hours),
then on one server you'll get
1970-01-01 08:00:00
and on other server you'll get
1970-01-01 09:00:00
and so on.
Though you could expect 1970-01-01 10:00:00 in all cases, because if 25200 seconds gone from 1970-01-01 00:00:00 it obviously have to be 1970-01-01 10:00:00

I spend today 3 hours to correct scripts which were created with such error by previous programmer, so please, guys, don't make me work like this and remember about conversation to LOCAL time.
phprocks at aol dot com
06-Aug-2008 06:25
Try this for finding the difference in days between 2 dates/datetimes... take note though, date_parse requires PHP version 5.1.3 or higher.

<?php
/**
 * Finds the difference in days between two calendar dates.
 *
 * @param Date $startDate
 * @param Date $endDate
 * @return Int
 */
function dateDiff($startDate, $endDate)
{
   
// Parse dates for conversion
   
$startArry = date_parse($startDate);
   
$endArry = date_parse($endDate);

   
// Convert dates to Julian Days
   
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
   
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);

   
// Return difference
   
return round(($end_date - $start_date), 0);
}
?>
JonathanCross.com
25-Jul-2008 08:22
<?php
// A demonstration of the new DateTime class for those
// trying to use dates before 1970 or after 2038.
?>
<h2>PHP 2038 date bug demo (php version <?php echo phpversion(); ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?php
  $format
='F j, Y';
  for (
$i = 1900; $i < 2050; $i++) {
   
$datep = "$i-01-01";
   
?>
    Trying: <?php echo $datep; ?> = <?php echo date($format, strtotime($datep)); ?><br>
    <?php
 
}
?></div>
<div style='float:left;'>
  <h3>NEW DateTime Class (v 5.2+)</h3><?php
 
for ( $i = 1900; $i < 2050; $i++) {
   
$datep = "$i-01-01";
   
$date = new DateTime($datep);
   
?>
    Trying: <?php echo $datep; ?> = <?php echo $date->format($format); ?><br>
    <?php
 
}
?></div>
Rob A.
10-Jul-2008 04:38
Quick function for returning the names of the next 7 days of the week starting with today.

Returns an array that can be formatted to your liking.

<?php
/**
* Returns array of next 7 days starting with today
*
*/

function next_7_days() {
       
// create array of day names. You can change these to whatever you want
   
$days = array(
                           
'Monday',
                           
'Tuesday',
                           
'Wednesday',
                           
'Thursday',
                           
'Friday',
                           
'Saturday',
                           
'Sunday');
   
$today = date('N');
    for (
$i=1;$i<$today;$i++) {

               
// take the first element off the array
       
$shift = array_shift($days);

               
// ... and add it to the end of the array
       
array_push($days,$shift);
    }
       
// returns the sorted array
   
return $days;
}
?>

It basically takes an array starting with Monday and shifts each day to the end of the array until the first element in the array is today.
con_tobe at yahoo dot com
10-Jul-2008 03:46
Doing $w-- for months ending on Sat won't hurt (i.e. if you're counting weeks as is the case below), but halocastle's code is perfectly fine as is and quite fast.  He/she uses $w as a key for the $weeks array.  "Halo" does this BEFORE $w++, so $w-- is superfluous as the loop has already ended.  For May, 2008, I get 5 weeks as expected...

Array
(
    [1] => Array
        (
            [4] => 1
            [5] => 2
            [6] => 3
        )

    [2] => Array
        (
            [0] => 4
            [1] => 5

------------OMITTED-----------------

            [4] => 22
            [5] => 23
            [6] => 24
        )

    [5] => Array
        (
            [0] => 25
            [1] => 26
            [2] => 27
            [3] => 28
            [4] => 29
            [5] => 30
            [6] => 31
        )

)

I guess the one pit-fall of the code is if you overlap months, say the following year, then $m-- makes perfect since...I think (haven't gotten that far...yet).

I modified "Halo's" code to include months, too (this is from a snippet that produces a three month calendar, hence the outer $months loop, omitted here).

<?php
$m
= date('m');
$Y = date('Y');

// for() {months loop omitted
$var_date = mktime(0, 0, 0, $m, 1, $Y);
$month_name = date('F', $var_date);
$months[$month_name]['DAYS'] = date('t', $var_date);
$months[$month_name]['FIRST_DAY'] = date('w', $var_date);
//}
foreach($months as $month => $key) {
 
$weeks = array();
  for(
$i = 1, $j = $key['FIRST_DAY'], $w = 1;$i <= $key['DAYS'];$i++) {
   
$weeks[$w][$j] = $i;
   
$j++;
    if(
$j == 7) {
     
$j = 0;
     
$w++;
    }
  }
 
$months[$month]['WEEKS'] = $weeks;
}
?>

Enjoy!
halocastle at yahoo dot com
01-Jul-2008 04:20
Weeks and days for any month/year combo:

<?php
$m
= 2; // February
$Y = 2008;

// constants used here for legibility, use $vars for dynamicon...
define('MONTH_DAYS',date('t', strtotime(date($m . '/01/' . $Y))));
// w:0->6 = Sun->Sat
define('MONTH_FIRST_DAY',date('w', strtotime(date($m . '/01/' . $Y))));

for(
$i = 1, $j = MONTH_FIRST_DAY, $w = 1;$i <= MONTH_DAYS;$i++) {
 
$week[$w][$j] = $i;
 
$j++;
  if(
$j == 7) {
   
$j = 0;
   
$w++;
  }
}
?>

print_r($week):
-----------------------
Array
(
    [1] => Array
        (
            [5] => 1
            [6] => 2
        )

    [2] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 5
            [3] => 6
            [4] => 7
            [5] => 8
            [6] => 9
        )

    [3] => Array
        (
            [0] => 10
            [1] => 11
            [2] => 12
            [3] => 13
            [4] => 14
            [5] => 15
            [6] => 16
        )

    [4] => Array
        (
            [0] => 17
            [1] => 18
            [2] => 19
            [3] => 20
            [4] => 21
            [5] => 22
            [6] => 23
        )

    [5] => Array
        (
            [0] => 24
            [1] => 25
            [2] => 26
            [3] => 27
            [4] => 28
            [5] => 29
        )

)



[EDIT BY danbrown AT php DOT net: In a note dated 03-JUL-08, (dmagick AT gmail DOT com) offered the following amendment to this note.]

[I've updated this] code as it doesn't take into account when a month finishes on a Saturday (eg May 2008).

<?php
$start_date
= mktime(0, 0, 0,$start_month, 1, $start_year);

$days_in_month = date('t', $start_date);
$month_first_day = date('w', $start_date);

$j = $month_first_day;
$num_weeks = 1;

for(
$i = 1; $i <= $days_in_month; $i++) {
   
$j++;
    if(
$j == 7) {
       
$j = 0;
       
$num_weeks++;
    }
}

// if the last day of the month happens to be a Saturday,
// take one off the number of weeks
// because it was being added inside the for loop.
if ($j == 0) {
   
$num_weeks--;
}
?>
Kavi Siegel
30-Jun-2008 02:18
I wrote the following function to show a series of drop down boxes to select the date. When provided with a timestamp, that date is selected by default, when none is provided, the current date is selected.

<?php
function chooseDate($timestamp = ""){
    if(
$timestamp == ""){
       
$timestamp = time();
    }
   
$months = array(null, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    unset(
$months[0]);
   
print_r($months);
   
$out = '<select name="month">';
    foreach(
$months as $key => $month){
        if(
$month == date('M', $timestamp)){
           
$out .= '<option value="'.$key.'" selected="selected">'.$month.'</option>';
        }else{
           
$out .= '<option value="'.$key.'">'.$month.'</option>';
        }
    }
   
$out .= '</select><select name="days">';
    for(
$i = 1; $i <= 32; $i++){
        if(
$i == date('j', $timestamp)){
           
$out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
        }else{
           
$out .= '<option value="'.$i.'">'.$i.'</option>';
        }
    }
   
$out .= "</select><select name='year'>";
    for(
$i = date('Y'); $i >= 1970; $i--){
        if(
$i == date('Y', $timestamp)){
           
$out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
        }else{
           
$out .= '<option value="'.$i.'">'.$i.'</option>';
        }
    }
   
$out .= "</select>";
    return
$out;
}
?>

Usage is simple:

<?php
echo chooseDate(); // Will select current date
echo chooseDate(1149566400); // Will select June 6th, 2006
?>
kontakt at arthur minus schiwon dot de
18-Jun-2008 10:29
to get the week of the month simply use:
ceil( date("j") / 7 );
diego at diego dot eng dot br
09-Jun-2008 11:27
I made a small code to get the last working day of the month:

<?php

$times
= strtotime(date("Y")."-".date("m")."-".date("t"));
for (
$lastworkingday=0;$lastworkingday==0;$times-=86400)
   if (
date("w",$times)!=0 && date("w",$times)!=6) $lastworkingday = date("j",$times);
print
$lastworkingday;

?>
phil dot taylor at enilsson dot com
26-May-2008 05:37
Found this helpful when converting unix dates for use with the ical file format.

<?php
// Converts a unix timestamp to iCal format (UTC) - if no timezone is
// specified then it presumes the uStamp is already in UTC format.
// tzone must be in decimal such as 1hr 45mins would be 1.75, behind
// times should be represented as negative decimals 10hours behind
// would be -10
       
   
function unixToiCal($uStamp = 0, $tzone = 0.0) {
   
       
$uStampUTC = $uStamp + ($tzone * 3600);       
       
$stamp  = date("Ymd\THis\Z", $uStampUTC);
       
        return
$stamp;       

    }
?>
chubby at chicks dot com
23-May-2008 01:54
<?php
/**
     * Checks wether a date is between an interval
     *
     * Usage:
     *     
     * // check if today is older than 2008/12/31
     * var_dump(currentDayIsInInterval('2008/12/31'));
     * // check if today is younger than 2008/12/31
     * var_dump(currentDayIsInInterval(null,'2008/12/31'));
     * // check if today is between 2008/12/01 and 2008/12/31
     * var_dump(currentDayIsInInterval('2008/12/01','2008/12/31')); 
     *
     * Will trigger errors if date is in wrong format, notices if $begin > $end    
     *         
     * @param string $begin Date string as YYYY/mm/dd
     * @param string $end Date string as YYYY/mm/dd
     * @return bool 
     */
function currentDayIsInInterval($begin = '',$end = '')
{
       
$preg_exp = '"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]"';
       
$preg_error = 'Wrong parameter passed to function '.__FUNCTION__.' : Invalide date
format. Please use YYYY/mm/dd.'
;
       
$interval_error = 'First parameter in '.__FUNCTION__.' should be smaller than
second.'
;
        if(empty(
$begin))
        {
               
$begin = 0;
        }
        else
        {
                if(
preg_match($preg_exp,$begin))
                {
                       
$begin = (int)str_replace('/','',$begin);
                }
                else
                {
                       
trigger_error($preg_error,E_USER_ERROR);
                }
        }
        if(empty(
$end))
        {
               
$end = 99999999;
        }
        else
        {
                if(
preg_match($preg_exp,$end))
                {
                       
$end = (int)str_replace('/','',$end);
                }
                else
                {
                       
trigger_error($preg_error,E_USER_ERROR);
                }
        }
        if(
$end < $begin)
        {
               
trigger_error($interval_error,E_USER_WARNING);
        }
       
$time = time();
       
$now = (int)(date('Y',$time).date('m',$time).date('j',$time));
        if(
$now > $end or $now < $begin)
        {
                return
false;
        }
        return
true;
}
?>
wilson dot p dot pereira at itelefonica dot com dot br
22-May-2008 03:37
The function below extracts any date time value basead in the string format.
Returns an associative array with day,month,year,hour,min and seg separated.

<?php
function ExtractDateTimeByFormat($strDateTime, $strFormat="dmYHis")
{
 
//extract the format
 
$i = 0;
 
$aFieldOrder = array();
 
$nFields = 0;
       
$strExtraction = "";
        while(isset(
$strFormat[$i]))
        {
           
$strField = $strFormat[$i];
            switch (
strtolower($strField) )
            {
                case
"D";
                case
"d";
                   
$aFieldOrder[$nFields] = "d";
                   
$nFields++;
                   
$strExtraction .= "%d";
                    if(isset(
$strFormat[$i+1]))
                    {
                       
$strExtraction .= "%*1c";
                    }
                break;

                case
"M";
                case
"m";
                   
$aFieldOrder[$nFields] = "m";
                   
$nFields++;
                   
$strExtraction .= "%d";
                    if(isset(
$strFormat[$i+1]))
                    {
                       
$strExtraction .= "%*1c";
                    }
                break;

                case
"y";
                case
"Y";
                   
$aFieldOrder[$nFields] = "y";
                   
$nFields++;
                   
$strExtraction .= "%4d";
                    if(isset(
$strFormat[$i+1]))
                    {
                       
$strExtraction .= "%*1c";
                    }
                break;

                case
"h";
                case
"H";
                   
$aFieldOrder[$nFields] = "h";
                   
$nFields++;
                   
$strExtraction .= "%d";
                    if(isset(
$strFormat[$i+1]))
                    {
                       
$strExtraction .= "%*1c";
                    }
                break;

                case
"i";
                   
$aFieldOrder[$nFields] = "i";
                   
$nFields++;
                   
$strExtraction .= "%d";
                    if(isset(
$strFormat[$i+1]))
                    {
                       
$strExtraction .= "%*1c";
                    }
                break;

                case
"S";
                case
"s";
                   
$aFieldOrder[$nFields] = "s";
                   
$nFields++;
                   
$strExtraction .= "%d";
                    if(isset(
$strFormat[$i+1]))
                    {
                       
$strExtraction .= "%*1c";
                    }
                break;
            }
           
$i++;
        }

   
$aValues = array();
   
$aValues = sscanf($strDateTime,$strExtraction);

    return
array_combine($aFieldOrder,$aValues);

}
?>
wulf dot kaiser at mpimf-heidelberg dot mpg dot de
21-May-2008 08:00
For output formatting of a SAMP based seminar announcement system, i had to fetch the date of every friday of a given month in a given year. Here's what i did:

<?php

$givenYear
= $_GET["givenYear"]; # assume "2006"
$givenMonth = $_GET["givenMonth"]; # assume "12"

if ($givenMonth != '12') {

   
$nextGivenMonth = "1";
   
$nextGivenYear = $givenYear + 1;}

    else {

       
$nextGivenMonth = $givenMonth + 1;
       
$nextGivenYear = $givenYear;}
       
       
# Get the first weekday of the month

       
$firstDayOfMonth = date("d", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
       
$firstWeekDayOfMonth = date("l", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
       
       
# Count days to first Friday

       
switch ($firstWeekDayOfMonth) {

            case
'Monday': $numOfDaysToFirstFriday = "4"; break;
            case
'Tuesday': $numOfDaysToFirstFriday = "3"; break;
            case
'Wednesday': $numOfDaysToFirstFriday = "2"; break;
            case
'Thursday': $numOfDaysToFirstFriday = "1"; break;
            case
'Friday': $numOfDaysToFirstFriday = "0"; break;
            case
'Saturday': $numOfDaysToFirstFriday = "6"; break;
            case
'Sunday': $numOfDaysToFirstFriday = "5"; break;}
           
           
# Get first Friday's date

           
$numOfDaysToFirstFriday = 1 + $numOfDaysToFirstFriday;
           
$firstFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
           
$firstFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
           
           
# Get the last weekday of the month

           
$lastDayOfMonth date("d", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
           
$lastWeekDayOfMonth date("l", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
           
           
# Count days to last Friday

           
switch ($lastWeekDayOfMonth) {

                case
'Monday': $numOfDaysToLastFriday = "3"; break;
                case
'Tuesday': $numOfDaysToLastFriday = "4"; break;
                case
'Wednesday': $numOfDaysToLastFriday = "5"; break;
                case
'Thursday': $numOfDaysToLastFriday = "6"; break;
                case
'Friday': $numOfDaysToLastFriday = "0"; break;
                case
'Saturday': $numOfDaysToLastFriday = "1"; break;
                case
'Sunday': $numOfDaysToLastFriday = "2"; break;}
               
               
# Get last Friday's date

               
$numOfDaysToLastFriday = $lastDayOfMonth - $numOfDaysToLastFriday;
               
$lastFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));
               
$lastFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));

               
$divisor = $lastFridayOfMonthDay - $firstFridayOfMonthDay;
               
$divisor = $divisor / 7;
                global
$divisor;
               
               
# Get the dates of all Fridays in the given Month (can be either 4 or 5)

               
if ($divisor=='3') {

                   
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
                   
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
                   
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
                   
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}

                    else if (
$divisor=='4') {

                       
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
                       
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 21, $givenYear));
                       
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
                       
$fourthFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
                       
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}

?>

Comments, suggestions and bugfixes are welcome ;-))
Raymond Irving
26-Mar-2008 03:44
I have written a little Date Class Library for PHP that supports timestamps for dates greater than 2038 and lesser than 1970.

This library can be used in both PHP4 and PHP5.

Check it out here:

http://xwisdomhtml.com/dateclass.html
Anonymous
29-Feb-2008 09:05
## This will produce the first day of last month and the last day of last month
## 2008-01-01 2008-01-31
<?php
echo date("Y-m-01", strtotime("-1 month", strtotime(date("Y-m-d"))))." ".date("Y-m-d", strtotime("-1 day", strtotime(date("Y-m-01")))) ?>
jc
31-Dec-2007 02:28
date("W") returns the iso8601 week number, while date("Y") returns the _current_ year. This can lead to odd results. For example today (dec 31, 2007) it returns 1 for the week and of course 2007 for the year. This is not wrong in a strict sense because iso defines this week as the first of 2008 while we still have 2007.

So, if you don't have another way to safely retrieve the year according to the iso8061 week-date - strftime("%G") doesn't work on some systems -, you should be careful when working with date("W").

For most cases strftime("%W") should be a safe replacement.

[edit: Much easier is to use "o" (lower case O) instead of "Y"]
ZZigc
28-Dec-2007 06:38
I wanted to get the number of weeks for particular year.

Example with date():
<?php

 $weeks_in_year
= date("W", strtotime("12/31/2007"));

?>

It works for years smaller than current year, but returns '01' when year was the same or bigger as current year.
Not sure if I missed something or maybe misused this function but I couldn't get it to work even with different date representations.

So the workaround was using different function.

Example with strftime():
<?php

 $weeks_in_year
= strftime("%W",strtotime("12/31/2007"));

?>

Now it works as a charm.

PHP v.4.4.7



[EDIT BY danbrown AT php DOT net: In a note dated 25-JAN-09, "Juan Paredes" offered the following information as an amendment.]

Complementing the information [in this note], if you want to calculate the number of weeks in a given year, according to the week definition by ISO 8601, the following should be enough:

date('W', mktime(0,0,0,12,28,$year) );

(the last week on a give year always contains 28-Dec)
bikinyboy at example dot com
12-Dec-2007 03:44
This function is like date, but it "speaks" Hungarian (or an other language)

<?php
/*
  these are the hungarian additional format characters
  �: full textual representation of the day of the week
  �-: full textual representation of the day of the week (first character is uppercase),
  �': short textual representation of the day of the week,
  �_: short textual representation of the day of the week (first character is uppercase),
  �_: full textual representation of a month
  �_: full textual representation of a month (first character is uppercase),
  �+: short textual representation of a month
  Ű: short textual representation of a month (first character is uppercase),
*/
function date_hu($formatum, $timestamp=0) {
  if ((
$timestamp <= -1) || !is_numeric($timestamp)) return '';
 
$q['�'] = array(-1 => 'w', 'vasárnap', 'h�ctf�'', 'kedd', 'szerda', 'cs�_t�rt�k', 'p�cntek', 'szombat');
 
$q['�-'] = array(-1 => 'w', 'Vasárnap', 'H�ctf�'', 'Kedd', 'Szerda', 'Cs�_t�rt�k', 'P�cntek', 'Szombat');
 
$q['�''] = array(-1 => 'w', 'va', 'h�c', 'ke', 'sze', 'cs�_', 'p�c', 'szo');
 
$q['�_'] = array(-1 => 'w', 'Va', 'H�c', 'Ke', 'Sze', 'Cs�_', 'P�c', 'Szo');
 
$q['�_'] = array(-1 => 'n', '', 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'okt�_ber', 'november', 'december');
 
$q['�_'] = array(-1 => 'n', '', 'Január', 'Február', 'Március', '�_prilis', 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Okt�_ber', 'November', 'December');
 
$q['�+'] = array(-1 => 'n', '', 'jan', 'febr', 'márc', 'ápr', 'máj', 'júni', 'júli', 'aug', 'szept', 'okt', 'nov', 'dec');
 
$q['Ű'] = array(-1 => 'n', '', 'Jan', 'Febr', 'Márc', '�_pr', 'Máj', 'Júni', 'Júli', 'Aug', 'Szept', 'Okt', 'Nov', 'Dec');

  if (
$timestamp == 0)
   
$timestamp = time();
 
$temp = '';
 
$i = 0;
  while ( (
strpos($formatum, '�', $i) !== FALSE) || (strpos($formatum, '�-', $i) !== FALSE) ||
          (
strpos($formatum, '�'', $i) !== FALSE) || (strpos($formatum, '�_', $i) !== FALSE) ||
          (
strpos($formatum, '�_', $i) !== FALSE) || (strpos($formatum, '�_', $i) !== FALSE) ||
          (
strpos($formatum, '�+', $i) !== FALSE) || (strpos($formatum, 'Ű', $i) !== FALSE)) {
   
$ch['�']=strpos($formatum, '�', $i);
   
$ch['�-']=strpos($formatum, '�-', $i);
   
$ch['�'']=strpos($formatum, '�'', $i);
   
$ch['�_']=strpos($formatum, '�_', $i);
   
$ch['�_']=strpos($formatum, '�_', $i);
   
$ch['�_']=strpos($formatum, '�_', $i);
   
$ch['�+']=strpos($formatum, '�+', $i);
   
$ch['Ű']=strpos($formatum, 'Ű', $i);
    foreach (
$ch as $k=>$v)
      if (
$v === FALSE)
        unset(
$ch[$k]);
   
$a = min($ch);
   
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
   
$i = $a+1;
  }
 
$temp .= date(substr($formatum, $i), $timestamp);
  return
$temp;
}

echo
date_hu('Y. �_ j. (�) G:i');
?>
redcore at gmail dot com
20-Nov-2007 01:24
For those of us who don't have 5.x installed (that puts a colon in the time zone)...

<?php
$timezone
= date("O"); // get timezone
$timezone_end = substr($timezone, -2, 2); // get last two numbers
$timezone= substr($timezone, 0, -2); // get first half
echo $timezone = $timezone . ":" . $timezone_end; // add colon
?>
snobord787 at msn dot com
30-Aug-2007 04:06
I modified (erenezgu at gmail.com)'s code so you don't have to redirect but is stored in cookies.

<?php
if(empty($_COOKIE['offset'])) {
   
// Javascript is our friend!
   
$header='
<script type="text/javascript">
document.cookie="offset=" + ( (new Date()).getTimezoneOffset()*60)*(-1)-'
.abs(date('Z')).';
</script>
'
;
}

// Example Usage
echo date('d/m/Y H:i:s', time()+$_COOKIE['offset'] );
?>
samuel at islabinaria dot com
16-Jul-2007 02:18
Here is a backward compatible version of dates_interconv
https://doc0.ru/phpe/function.date.php#71397
which also works with time (hours, minutes and seconds) and months in "M" format (three letters):

<?php
 
/**
   mod of
   https://doc0.ru/phpe/function.date.php#71397
   * Converts a date and time string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
   *
   * @param string $date_format1
   * @param string $date_format2
   * @param string $date_str
   * @return string
  */
 
function dates_interconv($date_format1, $date_format2, $date_str)
  {

     
$base_struc     = split('[:/.\ \-]', $date_format1);
     
$date_str_parts = split('[:/.\ \-]', $date_str );
    
     
// print_r( $base_struc ); echo "\n"; // for testing
      // print_r( $date_str_parts ); echo "\n"; // for testing
    
     
$date_elements = array();
    
     
$p_keys = array_keys( $base_struc );
      foreach (
$p_keys as $p_key )
      {
          if ( !empty(
$date_str_parts[$p_key] ))
          {
             
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
          }
          else
              return
false;
      }
    
     
// print_r($date_elements); // for testing
     
     
if (array_key_exists('M', $date_elements)) {
       
$Mtom=array(
         
"Jan"=>"01",
         
"Feb"=>"02",
         
"Mar"=>"03",
         
"Apr"=>"04",
         
"May"=>"05",
         
"Jun"=>"06",
         
"Jul"=>"07",
         
"Aug"=>"08",
         
"Sep"=>"09",
         
"Oct"=>"10",
         
"Nov"=>"11",
         
"Dec"=>"12",
        );
       
$date_elements['m']=$Mtom[$date_elements['M']];
      }
     
     
// print_r($date_elements); // for testing
    
     
$dummy_ts = mktime(
       
$date_elements['H'],
       
$date_elements['i'],
       
$date_elements['s'],
       
$date_elements['m'],
       
$date_elements['d'],
       
$date_elements['Y']
      );
    
      return
date( $date_format2, $dummy_ts );
  }
?>

Usage:

<?php
  $df_src
= 'd/m/Y H:i:s';
 
$df_des = 'Y-m-d H:i:s';
 
  echo
dates_interconv( $df_src, $df_des, '25/12/2005 23:59:59');
?>

Output:

2005-12-25 23:59:59
pierrotevrard at gmail dot com
03-Jul-2007 11:11
For people who used "z" format...

The real range of "z" key format is 0 to 365 (instead of 366) and "z" represent the number of spent days in the year.
See this examples :

<?php
define
("\n" , NL );
print
'<pre>';

print
'"z" format interpretation:' . NL . NL;

print
'On 0 timestamp: "' . date( 'z : Y-m-d' , 0 ) . '"' . NL;
//show: On 0 timestamp: "0 : 1970-01-01"

print 'On second unix day: "' . date( 'z : Y-m-d' , 3600*24 ) . '"' . NL;
//show: On second unix day: "1 : 1970-01-02"

print 'On the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31, 2000 ) ) . '"' . NL;
//show: On the last day of a leap year: "365 : 2000-12-31"

print 'On the day after the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31+1, 2000 ) ) . '"' . NL;
//show: On the day after the last day of a leap year: "0 : 2001-01-01"

print '</pre>';

?>
jcwebb at dicoe dot com
19-Jun-2007 05:48
i needed the day (eg. 27th) of the last Monday of a month
<?php
$d
=cal_days_in_month(CAL_GREGORIAN,$m,$y); // days in month
if (date('l',mktime(0,0,0,$m,$d,$y))=='Monday'): $finalmonday=$d;
else:
$finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,$d,$y))); // day(date) of last monday of month, eg 26
endif;
?>
this also works...
<?php
$finalmonday
=date('d',strtotime('last Monday',mktime(0,0,0,$m,($d+1),$y)));
//the '$d+1' is to catch the last day IS a monday (eg. dec 2007)
?>

Hope it helps, BigJonMX
boris at psyonline dot ru
14-Jun-2007 03:05
<?php

/**
 * Get date in RFC3339
 * For example used in XML/Atom
 *
 * @param integer $timestamp
 * @return string date in RFC3339
 * @author Boris Korobkov
 * @see http://tools.ietf.org/html/rfc3339
 */
function date3339($timestamp=0) {

    if (!
$timestamp) {
       
$timestamp = time();
    }
   
$date = date('Y-m-d\TH:i:s', $timestamp);

   
$matches = array();
    if (
preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
       
$date .= $matches[1].$matches[2].':'.$matches[3];
    } else {
       
$date .= 'Z';
    }
    return
$date;

}

?>
john at hotmail dot com
12-Jun-2007 01:55
Just a small addition to dmitriy. If the present date is in daylight saving time, and the date in the past is not, the result will not be a whole number by dividing by 86400. It will be something like 48.958333333. This is because the day in which it changes from normal to daylight saving time is one hour longer than normal (90000 secs) and the opposite is true when changing back (the day would be one hour shorter - 82800 secs).

If you want a whole number of days use the following instead:

<?php
$digest_date
= "2007-01-01";
$date_diff = round( abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400, 0 );
?>
pburlandoA_Remove_TgmailDOTcom
20-May-2007 07:30
This is an implementation for days360 formula used in financial calc software, this asumes year with 360 days and months with 30 days.

I am looking for a reliable function to add days to a date using 30[E]/360 format.

<?php
/* Calc days between two dates using the financial calendar
30/360 (usa) or 30E/360(european)<-default
$fecha1 and $fecha2 in format: aaaa-mm-dd
return days  or -1 in case of error.

based on cost_analysis.py module Ver. 0.1 public domain, no license required by Harm Kirchhoff
*/
function days_360($fecha1,$fecha2,$europeo=true) {
 
//try switch dates: min to max
 
if( $fecha1 > $fecha2 ) {
   
$temf = $fecha1;
   
$fecha1 = $fecha2;
   
$fecha2 = $temf;
  }

 
// get day month year...
 
list($yy1, $mm1, $dd1) = explode('-', $fecha1);
  list(
$yy2, $mm2, $dd2) = explode('-', $fecha2);

  if(
$dd1==31) { $dd1 = 30; }

 
//checks according standars: 30E/360 or 30/360.
 
if(!$europeo) {
    if( (
$dd1==30) and ($dd2==31) ) {
     
$dd2=30;
    } else {
      if(
$dd2==31 ) {
       
$dd2=30;
      }
    }
  }

 
//check for invalid date
 
if( ($dd1<1) or ($dd2<1) or ($dd1>30) or ($dd2>31) or
      (
$mm1<1) or ($mm2<1) or ($mm1>12) or ($mm2>12) or
      (
$yy1>$yy2) ) {
    return(-
1);
  }
  if( (
$yy1==$yy2) and ($mm1>$mm2) ) { return(-1); }
  if( (
$yy1==$yy2) and ($mm1==$mm2) and ($dd1>$dd2) ) { return(-1); }
 
 
//Calc
 
$yy = $yy2-$yy1;
 
$mm = $mm2-$mm1;
 
$dd = $dd2-$dd1;
 
  return( (
$yy*360)+($mm*30)+$dd );
}

// usage:
echo days_360("2007-01-13","2007-05-20");

?>
dmitrid at dont_show dot com
10-Mar-2007 08:14
Note for wips week limits function:
I had to run it over 52 weeks of the year and it was very slow so I've modified to improve:

<?php
function week_limits($weekNumber, $year, $pattern)
{
   
$pattern = ($pattern) ? $pattern : "m/d";
   
$stday = 7 * $weekNumber - 7;
   
$stDayNumber = date("w", mktime(0,0,0,1, 1+$stday, $year));
   
$stUtime = mktime(0,0,0,1,1+$stday-$stDayNumber, $year);
   
$start_time = date($pattern, $stUtime);
   
$end_time = date($pattern, $stUtime+6*24*60*60);
   return array(
$start_time, $end_time);
}
//week_limits()
?>
code at ashleyhunt dot co dot uk
17-Jan-2007 09:22
I wanted to shift an sql date forward by a set time period.
This is how I achived it... well handy.

<?php
function sql_date_shift($date, $shift)
{
return
date("Y-m-d H:i:s" , strtotime($shift, strtotime($date)));
}

// example usage

$date = "2006-12-31 21:00";
$shift "+6 hours"; // could be days, weeks... see function strtotime() for usage

echo sql_date_shift($date, $shift);

// will output: 2007-01-01 03:00:00
?>

Hope it is of use,
Ashley
28-Nov-2006 07:26
if you are sending your data to a database, you can just send time() and then use strftime() to turn the time() string into readable time format.

check both time() and strftime() functions both offer more or less same functionality as date(). date() can also be used with time() strings to display time in the past.

more or less with something like:

date("j F, Y - g:ia", $data['date_quoted'])

where time() = $data['date_quoted'] and time() is the exact time date when the string is executed. if this is done towards a database, the time() stored is the actual server time upon script execution, no matter the time set in the individual computer, this will record server time, unless a gmt is set in newer versions of php (5 and up).
jack at jtr dot de
26-Nov-2006 09:30
<?php
/**
     * Converts a date string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
     *
     * @param string $date_format1
     * @param string $date_format2
     * @param string $date_str
     * @return string
     */
   
function dates_interconv( $date_format1, $date_format2, $date_str )
    {
       
$base_struc     = split('[/.-]', $date_format1);
       
$date_str_parts = split('[/.-]', $date_str );
       
       
print_r( $base_struc ); echo "<br>";
       
print_r( $date_str_parts ); echo "<br>";
       
       
$date_elements = array();
       
       
$p_keys = array_keys( $base_struc );
        foreach (
$p_keys as $p_key )
        {
            if ( !empty(
$date_str_parts[$p_key] ))
            {
               
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
            }
            else
                return
false;
        }
       
       
$dummy_ts = mktime( 0,0,0, $date_elements['m'],$date_elements['d'],$date_elements['Y']);
       
        return
date( $date_format2, $dummy_ts );
    }
   
   
$df_src = 'd/m/Y';
   
$df_des = 'Y-m-d';
   
   
$iso_date = dates_interconv( $df_src, $df_des, '25/12/2005');
?>

output:

2005-12-25
admin [at] xorath [dot] com
23-Oct-2006 03:13
If you want to use the date function to fix the RFC-822 format from an allready made RSS 2.0 feed you can do it like this..

Maybe getting an external feed from another asp or php file that you cannot change, but want to have the correct dateformat for anyway.

<?php
    header
('Content-type: application/rss+xml; charset=iso-8859-1');
   
$xmlfile = simplexml_load_file($_GET[feedURL]);
    for (
$i = 0; $i < count($xmlfile->channel->item); $i++ )
       
$xmlfile->channel->item[$i]->pubDate = date("r",strtotime((string)($xmlfile->channel->item[$i]->pubDate)));
    echo
$xmlfile->asXML();
?>

Then simply link to your rss feed like this
filename.php?feedURL=http://www.example.com/rss.asp
filename.php?feedURL=http://www.example.com/rss.xml
filename.php?feedURL=http://www.example.com/rss.php

or what you want. Hope anyone can take advantage of this, I wrote it to help a friend which had date stored in database only by yyyy-mm-dd hh:mm:ss and retrieved via asp from another script.

Article at http://www.xorath.com/articles/?article=2
emailfire at gmail dot com
07-Oct-2006 04:39
To use the date("N") function in PHP < 5.1.0 use:

<?php
function dayofweek() {
$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
return
array_search(date("D"), $days) + 1;
}
?>
Michiel
28-Sep-2006 03:08
If you want to count quarters between dates you can use the following:

<?php
function countQuarters($begindate, $enddate)
        {
            if (!isset(
$begindate) || empty($begindate) || !isset($enddate) || empty($enddate))
                return -
1;
           
           
$countyears = date("Y", strtotime($enddate)) - date("Y", strtotime($begindate));
           
$quarters = 0;
           
            if (
date("Y", strtotime($enddate)) == date("Y", strtotime($begindate)))
            {
                if (
date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
                {
                    if (
date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
                    {
                       
$difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));
                       
                       
$quarters += ceil((int) $difference / 4);
                    }
                    else
                    {
                        return -
1;
                    }
                }
            }
            else
            {
               
$quarters = (int) $countyears * 4;
                if (
date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
                {
                    if (
date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
                    {
                       
$difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));
                       
                       
$quarters += ceil((int) $difference / 4);
                    }
                    else
                    {
                       
$afterbegin = 12 - (int) date("m", strtotime($begindate));
                       
$untilend = date("m", strtotime($enddate));
                       
                       
$quarters = ($quarters - 4) + ceil(($afterbegin + $untilend) / 4);
                    }
                }
            }
           
            return
$quarters;
        }
?>
russ at isitaboat dot co dot uk
06-Sep-2006 02:18
Easy way of switching between mysql and "normal" dates (english, not american)...

<?php
function flipdate($dt, $seperator_in = '-', $seperator_out = '-')
{
return
implode($seperator_out, array_reverse(explode($seperator_in, $dt)));
}
?>
michiel at mb-it dot nl
04-Sep-2006 12:59
***EDITOR NOTE: Referred to note has been removed.

The calculation function of the number of days between 2 dates by zzzdobr at gmai dot com could be done much easier:

<?php
function getdays($day1,$day2)
{
  return
round((strtotime($day2)-strtotime($day1))/(24*60*60),0);
}

$begin = date("Y/m/d"); // we set today as an example
$end = "2006/11/27";
getdays($begin,$end);
?>

So now all of you know how many days you have left to buy me a birthday present ;)
James
29-Aug-2006 12:45
Slightly modified the code provided by "martin at smttuk dot com" so that you can give the function a date and/or time that you choose;

<?php
   
function zonedate($layout, $countryzone, $daylightsaving, $time)
    {
        if(
$daylightsaving) {
           
$daylight_saving = date('I');
            if(
$daylight_saving){ $zone=3600*($countryzone+1); }
        }
        else {
            if(
$countryzone>>0){ $zone=3600*$countryzone; }
            else {
$zone=0; }
        }
        if(!
$time) { $time = time(); }
       
$date = gmdate($layout, $time + $zone);
        return
$date;
    }
?>

For example if I wanted the time and date of my birthday in New Zealand time;

<?php
   
echo zonedate('Y-m-d H:i:s',-12,true,mktime(18,46,0,9,7,1986));
?>
Corey
28-Aug-2006 12:55
It's pretty simple, but in case anybody else is having problems getting the exact time they need because of DST (ex: on a Windows box in an area without DST), you can fix it all in a single line. Example...

<?php
   
echo "The time is " . date((date("I") ? intval(date("g")) - 1 : date("g")) . ":i m/d/y") . ".";
?>
martin at smttuk dot com
25-Aug-2006 11:30
<?php
/* Country Zone : Time Zone Name
-12 : Dateline Standard
-11 : Samoa Standard Time
-10 : Hawaiian Standard Time
-8 : Pacific Standard Time
-7 : Mexican Standard Time, Mountain Standard Time
-6 : Central Standard Time, Mexico Standard Time
-5 : Eastern Standard Time Eastern Time, SA Pacific Standard Time
-4 : Atlantic Standard Time, SA Western Standard Time, Pacific SA Standard Time
-3.5 : Newfoundland Standard Time
-3 : SA Eastern Standard Time, E. South America Standard Time
-2 : Mid:Atlantic Standard Time
-1 : Azores Standard Time, Cape Verde Standard Time
0 : Universal Coordinated Time, Greenwich Mean Time
1 : Romance Standard Time, Central Africa Standard Time, Central European Standard Time
2 : Egypt Standard Time, South Africa Standard Time, E. Europe Standard Time, FLE Standard Time, GTB Standard Time
3 : Arab Standard Time, E. Africa Standard Time, Arabic Standard Time, Russian Standard Time
3.5 : Iran Standard Time
4 : Arabian Standard Time, Caucasus Standard Time, Afghanistan Standard Time
5 : West Asia Standard Time
5.5 : India Standard Time
5.75 : Nepal Standard Time
6 : Central Asia Standard Time
6.5 : Myanmar Standard Time
7 : SE Asia Standard Time, North Asia Standard Time
8 : China Standard Time, W. Australia Standard Time, Singapore Standard Time, Taipei Standard Time, North Asia East Standard Time
9 : Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time
9.5 : AUS Central Standard Time, Cen. Australia Standard Time
10 : AUS Eastern Standard Time, E. Australia Standard Time
West Pacific Standard Time, Tasmania Standard Time, Vladivostok Standard Time
11 : Central Pacific Standard Time
12 : Fiji Standard Time, New Zealand Standard Time
13 : Tonga Standard Time

* How to use

   $layout =
       Same function as date : http://uk2.php.net/manual/en/function.date.php
   $countryzone =
       Country Zone from Above Eg: 0 ,for Greenwich Mean Time
   $daylightsaving =
       Set true if the Country has daylight saving it will auto change.
       Set false if the Country dose not have daylight saving or wish to it Disabled.
       (About Daylight Saving go here : http://www.timeanddate.com/time/aboutdst.html)
   Call Function:
       zonedate($layout, $countryzone, $daylightsaving);
  
   E.g.
   If GMT = Friday 25th of August 2006 10:23:17 AM
   When Function called:
   // West Asia Standard Time (Country Uses daylight saving)
       echo zonedate("l dS \of F Y h:i:s A", 5, true);
   //Output : Friday 25th of August 2006 03:23:17 PM
*/

function zonedate($layout, $countryzone, $daylightsaving)
{
if (
$daylightsaving){
$daylight_saving = date('I');
if (
$daylight_saving){$zone=3600*($countryzone+1);}
}
else {
   if (
$countryzone>>0){$zone=3600*$countryzone;}
       else {
$zone=0;}
}
$date=gmdate($layout, time() + $zone);
return
$date;
}
?>
mwwaygoo AT hotmail DOT com
09-Aug-2006 03:11
Number of weeks per month

I was trying to do a monthly calendar and required the number of weeks in a month, running from Monday to Sunday. Since PHP doesn't have this in its date() parameters I had to calculate it in a roundabout manner. By subtracting the week numbers away from each other we SHOULD get the number of weeks, since it is calculated on Mondays.

<?php
$year
= date("Y", $date);
$month = date("m", $date);
if( (isset(
$_GET['year'])) && (intval($_GET['year']) > 1582) )
{
   
$year = intval($_GET['year']);
}
if( (isset(
$_GET['month'])) && (intval($_GET['month']) >= 1) && (intval($_GET['month']) <= 12) )
{
   
$month = intval($_GET['month']);
}
$date = mktime(1, 1, 1, $month, date("d"), $year);

$first_day_of_month = strtotime("-" . (date("d", $date)-1) . " days", $date);
$last_day_of_month = strtotime("+" . (date("t", $first_day_of_month)-1) . " days", $first_day_of_month);

$first_week_no = date("W", $first_day_of_month);
$last_week_no = date("W", $last_day_of_month);

if(
$last_week_no < $first_week_no) $last_week_no=date("W", strtotime("-1 week",$last_week_no)) + 1;
$weeks_of_month = $last_week_no - $first_week_no + 1;

?>

The check for weeknumber of the end of the month being smaller than the beginning of the month, is because of December. Where Monday 31st is actually in the first week of the following year.
The +1 adjustment is for the number of weeks, inclusive. ie if January had five week, then 5-1=4, so we need to add an extra one to make it 5.
Phil Sylvia
08-Aug-2006 04:05
I simplified this after I figured it out based upon Mel Boyce's simple solution. Thanks Mel!

 I wanted to calculate dates based upon any given date and not just todays date which is what the hundreds of examples on the Internet use.  I created a simple function and then just call the function with 2 parameters.. the date (string) to test and the number of days that I want to add (positive #) or subtract (negative #) My intended use is to retrieve dates from the database and perform the date calculations.  This makes it simple.  I hope this helps someone as frustrated as I was. Enjoy.

******************************************
<?php

// date calculation function
// adds or subtracts a date based upon the input.
// $this_date is a string format of a valid date ie.. "2006/08/11"
// $num_days is the number of days that you would like to add (positive number) or subtract (negative number)

function fnc_date_calc($this_date,$num_days){
   
   
$my_time = strtotime ($this_date); //converts date string to UNIX timestamp
   
$timestamp = $my_time + ($num_days * 86400); //calculates # of days passed ($num_days) * # seconds in a day (86400)
    
$return_date = date("Y/m/d",$timestamp);  //puts the UNIX timestamp back into string format
   
   
return $return_date;//exit function and return string
}//end of function

$date_to_test = "2006/08/11";
$days_to_add = 7;

$past_date = fnc_date_calc($date_to_test,(($days_to_add)*-1));
$future_date = fnc_date_calc($date_to_test,$days_to_add);

echo
"Test Date is:   ".$date_to_test;
echo
"<br>";
echo
"Number of days to Calculate is: ".$days_to_add;
echo
"<br>";
echo
"Past date is:   ".$past_date;
echo
"<br>";
echo
"Future date is: ".$future_date;
?>
27-Jul-2006 09:03
For PHP 4 users wanting a format similar to ISO 8601 (http://www.w3.org/TR/NOTE-datetime):

    echo date('Y-m-d H:i:s.0T');

returns something like 2006-07-27 16:54:14.0EDT
Alvin Delagon
20-Jul-2006 09:48
Here's a function that takes the year as input and returns an array or dates that are mondays. (It can be used for generating weekly reports just like I did)

<?php
function getMondays($year) {
 
$newyear = $year;
 
$week = 0;
 
$day = 0;
 
$mo = 1;
 
$mondays = array();
 
$i = 1;
  while (
$week != 1) {
   
$day++;
   
$week = date("w", mktime(0, 0, 0, $mo,$day, $year));
  }
 
array_push($mondays,date("r", mktime(0, 0, 0, $mo,$day, $year)));
  while (
$newyear == $year) {
   
$test strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");
   
$i++;
    if (
$year == date("Y",$test)) {
     
array_push($mondays,date("r", $test));
    }
   
$newyear = date("Y",$test);
  }
  return
$mondays;
}
?>
dulare at gmail dot com
13-Jul-2006 03:36
If You are looking for some simple date calculations:

<?php

function days_between($fyear, $fmonth, $fday, $tyear, $tmonth, $tday)
{
  return
abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24));
}

function
day_before($fyear, $fmonth, $fday)
{
  return
date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-1,$fyear));
}

function
next_day($fyear, $fmonth, $fday)
{
  return
date ("Y-m-d", mktime (0,0,0,$fmonth,$fday+1,$fyear));
}

function
weekday($fyear, $fmonth, $fday) //0 is monday
{
  return (((
mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, 7, 17, 2006))/(60*60*24))+700000) % 7;
}

function
prior_monday($fyear, $fmonth, $fday)
{
  return
date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-weekday($fyear, $fmonth, $fday),$fyear)); 
}

?>
Elena S.
05-May-2006 09:36
If you do not PHP5 yet but want a week day to be in ISO format: 1 (for Monday) through 7 (for Sunday), you can use this:

<?php

//GET WEEK DAY 0 FOR SUNDAY, 6 FOR SATURDAY
$x = date( "w" );

$corrected_week_day = 7 - ( (7-$x) % (7+$x) );

?>
mel dot boyce at gmail dot com
06-Apr-2006 11:46
I've been flicking through the comments looking for some succinct date code and have noticed an alarming number of questions and over-burdened examples related to date mathematics. One of the most useful skills you can utilize when performing date math is taking full advantage of the UNIX timestamp. The UNIX timestamp was built for this kind of work.

An example of this relates to a comment made by james at bandit-dot-co-dot-en-zed. James was looking for a way to calculate the number of days which have passed since a certain date. Rather than using mktime() and a loop, James can subtract the current timestamp from the timestamp of the date in question and divide that by the number of seconds in a day:
<?php
$days
= floor((time() - strtotime("01-Jan-2006"))/86400);
print(
"$days days have passed.\n");
?>

Another usage could find itself in a class submitted by Kyle M Hall which aids in the creation of timestamps from the recent past for use with MySQL. Rather than the looping and fine tuning of a date, Kyle can use the raw UNIX timestamps (this is untested code):
<?php
$ago
= 14; // days
$timestamp = time() - ($ago * 86400);
?>

Hopefully these two examples of "UNIX-style" timestamp usage will help those finding date mathematics more elusive than it should be.
SpikeDaCruz
09-Mar-2006 07:12
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.

<?php
function getOrthodoxEaster($date){
 
/*
   Takes any Gregorian date and returns the Gregorian
   date of Orthodox Easter for that year.
  */
 
$year = date("Y", $date);
 
$r1 = $year % 19;
 
$r2 = $year % 4;
 
$r3 = $year % 7;
 
$ra = 19 * $r1 + 16;
 
$r4 = $ra % 30;
 
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
 
$r5 = $rb % 7;
 
$rc = $r4 + $r5;
 
//Orthodox Easter for this year will fall $rc days after April 3
 
return strtotime("3 April $year + $rc days");
}
?>
erwinmoller at xs4all dot nl
05-Jan-2006 12:34
If you need dates that are prior to 1970 (or 1901 for php5.1), have a look at calendar at this very site:
http://www.php.net/calendar
Nick H
24-Nov-2005 02:21
Users in GMT may find some information on British Summer Time useful. Personally I was confused that date() for a timestamp of 0 was returning 1am, until I found about the all-year BST from 1968-71.

http://wwp.greenwichmeantime.com/info/bst2.htm
vernon at vernonkesner dot com
02-Nov-2005 05:37
The examples for getting a date in the past or future is simply not the best way to do it.  Especially if you are doing it dynamically.

I find the best way to get a date in the past or future is like this:

<?php
//get timestamp for past/future date I want
$pf_time = strtotime("-3 days");
//format the date using the timestamp generated
$pf_date = date("Y-m-d", $pf_time);
?>
martin at kurahaupo dot gen dot nz
30-Oct-2005 09:52
There is a mistaken impression that the maximum difference between UTC and localtime is +/- 12 hours. Right now it is summer here in New Zealand, and we're 13 hours ahead of UTC, and further east in the Chatham Islands it's UTC+13:45.

Consequently, the range for the "Z" conversion is at least -43200 ... +49500
mbirth at webwriters dot de
25-Oct-2005 10:24
Using 'B' for the Swatch Internet Time (i.Beats) can still lead to misunderstandings, because the date given in the resulting string is the local date, not the date of the BMT (Biel Mean Time / UTC+0100) after which the i.Beats are counted. So while @000 is equal all around the globe, October 25th 2005 @000 in Chicago is really October 24th, 06:00 PM local time.

Otherwise, if you use date('d M Y @B') in Chicago on that day at 6pm, it will return "24 Oct 2005 @000" although it should be "25 Oct 2005 @000".

So it may happen that you miss an appointment by 24 hours (or 1000 Beats ;-)

Here's a way to return the Internet Time with correct date:

<?php
  $curtime
= time();
 
$utcdiff = date('Z', $curtime);  // get difference to UTC in seconds
 
$bmttime = $curtime - $utcdiff + 3600;   // BMT = UTC+0100
 
$ssm = date('H', $bmttime)*3600 + date('i', $bmttime)*60 + date('s', $bmttime);  // seconds since midnight (BMT)
 
$ibeats = $ssm/86.4 // 86400 seconds = 1000 beats, so 1 beat = 86.4 seconds

 
echo 'i.Beats     : ' . date('D, d M Y', $bmttime) . ' @' . $ibeats;
?>

Note: If you would try date('D, d M Y @B', $bmttime), the resulting beats would be wrong because the timezone used for calculation of the beats within the date() function is still your local one but the timestamp is UTC+0100. Another working way would be:

<?php
  $curtime
= time();
 
$utcdiff = date('Z', $curtime);  // get difference to UTC in seconds
 
$bmttime = $curtime - $utcdiff + 3600;   // BMT = UTC+0100

 
echo 'i.Beats     : ' . date('D, d M Y', $bmttime) . ' @' . date('B', $curtime);
?>

But this way there are no floating-point beats possible, which may be handy sometimes.
kbrill at multi dot com
15-Sep-2005 03:27
I created a routine that fills an array with the dates in the current week.  For example $WeekDays[0] is sunday's date, $WeekDays[1] is monday's date and so on no matter what day of the week it is today.

<?php
        $lowEnd
=date("w");
       
$lowEnd=-$lowEnd;
       
$highEnd=$lowEnd + 6;
       
$weekday=0;
        for (
$i=$lowEnd; $i<=$highEnd; $i++) {
           
$WeekDate[$weekday]=date("m/d",mktime(0, 0, 0, date("m")  , date("d")+$i, date("Y")));
           
$weekday++;
        }
?>
webmaster [AT] gn-solutions [DOT] de
07-Sep-2005 11:19
For users who want a different language than english, you can user strftime() function in combination with setlocale() instead of date():

e.g. for german language:

With date you would write:
<?php
echo date('l, d. F Y'); //Output: Wednesday, 07. September 2005
?>

With strftime() you can output it in german like this:
<?php
// Set the gloabal LC_TIME constant to german
setlocale(LC_TIME, 'de_DE');
// Little bit other Syntax but better effect
echo strftime('%A, %d. %B %Y'); //Output: Mittwoch, 07. September 2005
?>

Greetings, Andy!
jon AT standardise DOT us
15-Feb-2005 04:57
Don't forget that months start on the 1st day, and not a zero date.  Might seem obvious but:

<?php $test = date("F Y", mktime(0, 0, 0, 12, 0, 2005)); ?>

Will return November 2005, not December.

<?php $test = date("F Y", mktime(0, 0, 0, 12, 1, 2005)); ?>

The 1st is needed to get the right month.
ag nodot nospam at netside dot de
28-Jan-2005 03:19
Calculus of weeks in a year.

Since there is date("W") many still seem to have a problem regarding how many weeks there are in an year. Some rather complex solutions have been shown here.

It's defined, that a week which begins in december and ends in january the following year belongs to the year where most of its days lie. Therefore a week with at least 4 days in december is the last week of that year and a week with at least 4 days in january is the first week in the new year.

This concludes, that the last week of a year always contains the 28th day of december. So if you take date("W") on that day of a given year you always get the correct number of weeks for that year.
The other end of that definition is that the 4th day of january always lies in the first week of a year.

I hope this solves a lot of confusion.

(For those asking what all this fuzz about counting weeks is about: normally theres 52 weeks in a year but sometimes its 53 weeks in a year)

I wrote it down as a function, but as this is rather trivial one might consider using the date(...) only.

<?php
function weeks($year) {
    return
date("W",mktime(0,0,0,12,28,$year));
}
?>
php at document-root dot de
14-Apr-2004 05:02
To convert an unix timestamp to suite the syntax of a GeneralizedTime attribute for OpenLDAP, you can use
date ('YmdHiZO'). Note that this conversion uses local time, the recommended way is to store dates in UTC.

If your date is in UTC, just use
date ('YmdHiZ').'Z' to convert it ("Z" stands for "Zulu", which is UTC).
daniel
17-Feb-2004 10:43
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.

<?php
function getOrthodoxEaster($date){
 
/*
    Takes any Gregorian date and returns the Gregorian
    date of Orthodox Easter for that year.
  */
 
$year = date("Y", $date);
 
$r1 = $year % 19;
 
$r2 = $year % 4;
 
$r3 = $year % 7;
 
$ra = 19 * $r1 + 16;
 
$r4 = $ra % 30;
 
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
 
$r5 = $rb % 7;
 
$rc = $r4 + $r5;
 
//Orthodox Easter for this year will fall $rc days after April 3
 
return strtotime("3 April $year + $rc days");
}
?>
 

 
credits | contact