Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

date

(PHP 3, 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).

Таблица 1. В параметре format распознаются следующие символы

Символ в строке formatОписаниеПример возвращаемого значения
aAnte meridiem или Post meridiem в нижнем регистреam или pm
AAnte 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(0, 0, 0, 7, 1, 2000));
?>

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

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

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

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

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

<?php
$tomorrow 
= mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("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().



getdate> <date_timezone_set
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
date
kirti dot contact at gmail dot com
30-Oct-2007 10:17
I was looking for a function to find the week range for a particular week. But now I have developed by own. This function takes three arguments all optional
1. Week - This value ranges from 1- 52 or 53. It needs a correct value. If no value is provided, it then uses the current week.
2. Year - If none is provided, then the current year.
3. Format - defaults to d/M/Y

It returns an array containing the 'start date' and the 'end date'

Imp. Week starts from Sunday.

function getWeekDateRange($week="",$year="",$format="d/M/Y"){
    if($year=="" || !is_numeric($year))
        $year=date("Y");
    if($week=="" || !is_numeric($week))
        $week=date("W");       
       
    $week--;       
  $first_day=date("w",mktime(0,0,0,1,1,$year));
    $first_day_tstamp=mktime(0,0,0,1,1,$year);   
    $first_sunday=($first_day==0?0:(6-$first_day+1));
    $first_sunday_tstamp=$first_sunday*24*3600+$first_day_tstamp;   
       
    if($first_sunday!=0){
        $week_cal=$week-1;
    }else{
        $week_cal=$week;
    }   
   
    $tw_start_tstamp=$first_sunday_tstamp+$week_cal*7*24*3600;
    $tw_end_tstamp=$first_sunday_tstamp+($week_cal+1)*7*24*3600-1;
   
    $yy=date("Y",$tw_end_tstamp);
    if($yy>$year)
        $tw_end_tstamp=mktime(23,59,59,12,31,$year);   
    if($week==0 && $first_sunday!=0){
        $tw_start_tstamp=$first_day_tstamp;
        $tw_end_tstamp=$first_sunday_tstamp-1;       
    }   
   
    $start_date=date($format,$tw_start_tstamp);
    $end_date=date($format,$tw_end_tstamp);
   
    return array($start_date,$end_date);
}
info at NOSPAM dot ogmatter dot com
29-Oct-2007 07:30
Hello, these notes have been very helpful and help me solve the following problem.

I have a db with scheduled items that contain a start date, a day to occur on and how many weeks from the next closest day to happen again.  I wrote the following script to do the following
1. Accept : starting date, the current date, the number of weeks between occurances and the day of the week it is to occur on.
2. Find the closest future day of the week argument from the start date.
3. Find out when the next time the item should happen via the weeks inbetween and the closest day of the week to the start date.

The result could be compared with your current date to trigger your periodical item or simply to find out when the next occurances will happen.

// $startDate:Date
// $todayDate:Date
// $weeks:Int - number of weeks in between
// $wantDay:String - full day of the week
function getWeekPeriodDate($startDate,$todayDate,$weeks,$wantDay){
  $startDate = date("Y-m-d", strtotime("next $wantDay" ,strtotime($startDate)));
  $dayDiff = round((strtotime($startDate)-strtotime($todayDate))/(24*60*60),0);
  $weekPeriodDiff = abs(round($dayDiff/7/$weeks)*$weeks);
  return date("Y-m-d",strtotime($startDate . " + " . $weekPeriodDiff . " weeks"));
}

Usage :getWeekPeriodDate("2006-July-1","2007-Nov-5",8,"Tuesday")
returns : 2007-11-20 (which is the next Tuesday based on 8 week periods since the next Tuesday closest to the start date)
kangaroo232002 at yahoo dot co dot uk
18-Oct-2007 01:52
Just a quick note on Josh L's implementation, switch doesn't pick up differences of '0' (or false) so if you are sending an email out at the same time as posting something, it will give you just a date (in the default) rather than a cute string. So, just add a catch at the top like

<?php

if($diff === 0) {
    return
"just now";
} else {
 <do
everything else>
}

?>

otherwise thanks josh for a v useful function :)
haqpunk at mail dot google dot com
16-Oct-2007 04:26
If you have a unix time stamp value in your DB that you would like to see the elapsed time for this might save you some time:

<?php
if(mysql_result($result, 0, "Time_Stamp")){
$Now=strtotime(date('Y-m-d H:i:s'));
$Action=strtotime(mysql_result($result, 0, "Time_Stamp"));

## Calculate time past since status change
$dateDiff = $Now - $Action;
$Days = floor($dateDiff/(60*60*24));
$Hours = floor(($dateDiff-($Days*60*60*24))/(60*60));
$Minutes = floor(($dateDiff-($Days*60*60*24)-($Hours*60*60))/60);
$Seconds = floor($dateDiff-($Days*60*60*24)-($Hours*60*60)-($Minutes*60));

## Display in unix like time stamp format
echo str_pad($Days, 2, "0", STR_PAD_LEFT)." ".str_pad($Hours, 2, "0", STR_PAD_LEFT).":".str_pad($Minutes, 2, "0", STR_PAD_LEFT).":".str_pad($Seconds, 2, "0", STR_PAD_LEFT);} ?>
New_Age
16-Oct-2007 01:11
I was searching to change order within the date.
Instead of YYYY-mm-dd, to get different order.
One query is simple:
 "SELECT place, DATE_FORMAT(event_date,'%d.%m.%Y.') AS event_date FROM  table";

The date comes out as d.m.YYYY. as this is usual in my country.
john at malkovich dot net
12-Oct-2007 06:46
If you're wanting to increment a date, add twenty-FIVE hours (yes, one day per year may last 25 hours...), and the additional hour won't impact other days, as it's converted to a Y-m-d string:

$date=date('Y-m-d', strtotime($date)+(25*3600));

Try this for october 28, 2007...
davedx at g removeme mail dot com
08-Oct-2007 07:50
I made a minor modification to wes.wysoft.com's "nth day of the month" function. I was attempting to convert Windows registry TIME_ZONE_INFORMATION structs to PHP dates to do timezone + DST conversions, and the registry entries don't seem to be quite right - for GMT, the correct end of DST is "the last Sunday in October", but the windows registry stores it as "the 5th Sunday in October"... but in 2007 there are only 4 Sundays! To protect from further craziness, I do this:

function weekDayOf($year,$month,$dayoftheweek,$occurance) {
    /*
     * returns the # occurance of the day of the week. Such as the 3rd sunday
     * if occurance is null it will return the whole array. for the week days in that month
     * it can be accessed by $date[$dayoftheweek][$occurance]=date;
     */
    $mdays=date("t",mktime(0,0,0,$month,1,$year)); //days in the current month
    $first_day = date('w',mktime(0,0,0,$month,1,$year)); // day of the week the month started with
    $day_oc = array(); // occurances of each day of the week
    for($i=0;$i<$mdays;++$i){
        $dayofweek = ($i+$first_day)%7;
        if(!is_array($day_oc[$dayofweek])) {
            $day_oc[$dayofweek] = array();
        }
        $day_oc[$dayofweek][]=$i+1;
    }
    $n = $occurance;
    while($n > 0 && !isset($day_oc[$dayoftheweek][$n]))
        $n--;
    return $day_oc[$dayoftheweek][$n];
}
david dot scourfield at llynfi dot co dot uk
04-Oct-2007 10:28
Two comments below give us superfluous code.

Firstly, arkin AT REMOVESPAM DOT arkinex DOT com has posted a function that "takes 2007-09-19 21:05:23 and turns it into a unix timestamp."  The built-in PHP function  strtotime()  can do this, so defining another function is unnecessary:

<?php

$timestamp
= strtotime("2007-09-19 21:05:23");

?>

And secondly, vikram dot dhanjal at gmail dot com gives us "Code for generating time stamp for current time." Again, strtotime()  can do this, but PHP also has a built-in function for that very purpose: time().

<?php

$timestampRightNow
= strtotime("Now");

// or simpler still:

$timestampRightNow = time();

?>

time() is quicker than strtotime("Now") as PHP does not need to parse the string provided.
vikram dot dhanjal at gmail dot com
28-Sep-2007 06:41
Code for generating time stamp for current time. May be useful for someone working on date and time things.
/*Full right to modify and use it.*/

list($ch,$ci,$cs,$cm,$cd,$cy)=explode(",",date("H,i,s,m,d,y"));    $now=mktime($ch,$ci,$cs,$cm,$cd,$cy);

echo $now;
eves1985 at gmail dot com
25-Sep-2007 12:30
A refinement on my last  post is this one. It will output the current date and time of the user... just one simple line of code!

<?   
  $date = date('d-m-Y, H:i',(time()-date('Z')));
?>

Kind regards,
Ewald
sheldon at gozipline dot com
21-Sep-2007 11:41
I have to work out the day before an event to send an email notification.  But if the day before was on a weekend I had to make sure the email was send on the Friday before the weekend.  I didn't see anything like this around so here is what i wrote.
Hope it helps some one else.

<?php
$dates    
= explode("/", "09/22/2007");
$month     = $dates['0'];
$day       = $dates['1'];
$year      = $dates['2'];
$yesterday = mktime(0,0,0,$month,$day-1,$year);
$notification = date('l',$yesterday);
if(
in_array($notification, array("Saturday", "Sunday"))){
   
$notification = "Friday";
}
echo(
"<p>{$notification}</p>");
?>
www.globalprompt.net
20-Sep-2007 11:50
function dateDiff($dformat, $endDate, $beginDate)
    {
    $date_parts1=explode($dformat, $beginDate);
    $date_parts2=explode($dformat, $endDate);
    $start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
    $end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
    return $end_date - $start_date;
    }

Now let us see how we use this function:

    $date1="07/11/2003";
    $date2="09/04/2004";

    print "If we minus " . $date1 . " from " . $date2 . " we get " . dateDiff("/", $date2, $date1) . ".";
arkin AT REMOVESPAM DOT arkinex DOT com
18-Sep-2007 03:51
This snippet takes 2007-09-19 21:05:23 and turns it into a unix timestamp, created and found very useful on a project i just did.

<?php
function make_timestamp($date) {
list(
$year, $month, $day, $hour, $minute, $second) = split('[-: ]', $date);
return
mktime($hour, $minute, $second, $month, $day, $year);
}
?>
minterior at gmail dot com
15-Sep-2007 01:46
<?php
/**
 * Calculate how old is a person with the birth date given
 */
function calculateYearsOld($bday, $bmonth, $byear) {
   
$years = date("Y") - intval($byear);

   
//If birthday is after today, he/she has one year old less
   
$day   = str_pad(intval($bday),   2, "0", STR_PAD_LEFT);
   
$month = str_pad(intval($bmonth), 2, "0", STR_PAD_LEFT);
    if(
intval("$month$day") > intval(date("md")))
     
$years -= 1;

    return
$years;
}
?>
eves1985 at gmail dot com
13-Sep-2007 06:57
If you want to define your own time without having trouble with the server time you could do this;

<?
  $timeZoneOffset = +1; //timezone where the user is (use an additional script to determine this variable)

  $H = (date('H')+date('O'))+$timeZoneOffset; //hour
  $i = date('i'); //minutes
  $s = date('s'); //seconds
  $m = date('m');  //month
  $d = date('d') //day
  $Y = date('Y') //year
  $date = date('Y-m-d, H:i:s',mktime($H,$i,$s,$m,$d,$Y)); // will output somthing like 2007-09-13, 03:52:05
?>
snobord787 at msn dot com
29-Aug-2007 09: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'] );
?>
wes.wysoft.com
18-Aug-2007 08:58
Well I looked all over the place for this and couldn't find it so I made my own. Hopefully it saves someone else some time. It will give you the occurances of a day in a month. For example if you want to get the date of the 2 Tuesday in a month.

<?php

function weekDayOf($year,$month,$dayoftheweek=null,$occurance=null) {
   
/*
     * returns the # occurance of the day of the week. Such as the 3rd sunday
     * if occurance is null it will return the whole array. for the week days in that month
     * it can be accessed by $date[$dayoftheweek][$occurance]=date;
     */
   
$mdays=date("t",mktime(0,0,0,$month,1,$year)); //days in the current month
   
$first_day = date('w',mktime(0,0,0,$month,1,$year)); // day of the week the month started with
   
$day_oc = array(); // occurances of each day of the week
   
for($i=0;$i<$mdays;++$i){
       
$dayofweek = ($i+$first_day)%7;
        if(!
is_array($day_oc[$dayofweek])) {
           
$day_oc[$dayofweek] = array();
        }
       
$day_oc[$dayofweek][]=$i+1;
    }
    return
$dayoftheweek ? $day_oc[$dayofweek][$occurance] : $day_oc;
}

?>
wes.wysoft.com
18-Aug-2007 08:55
Well I looked all over the place for this and couldn't find it so I made my own. Hopefully it saves someone else some time. It will give you the occurances of a day in a month. For example if you want to get the date of the 2 Tuesday in a month.

<?php

function weekDayOf($year,$month,$dayoftheweek=null,$occurance=null) {
   
/*
     * returns the # occurance of the day of the week. Such as the 3rd sunday
     * if occurance is null it will return the whole array. for the week days in that month
     * it can be accessed by $date[$dayoftheweek][$occurance]=date;
     */
   
$mdays=date("t",mktime(0,0,0,$month,1,$year)); //days in the current month
   
$first_day = date('w',mktime(0,0,0,$dateObj['m'],1,$dateObj['y'])); // day of the week the month started with
   
$day_oc = array(); // occurances of each day of the week
   
for($i=0;$i<$mdays;++$i){
       
$dayofweek = ($i+$first_day)%7;
        if(!
is_array($day_oc[$dayofweek])) {
           
$day_oc[$dayofweek] = array();
        }
       
$day_oc[$dayofweek][]=$i+1;
    }
    return
$dayoftheweek ? $day_oc[$dayofweek][$occurance] : $day_oc;
}

?>
david dot scourfield at llynfi dot co dot uk
17-Aug-2007 03:07
I created this function a while ago and needed it again recently, so had to trawl through some old files to find it. Thought I'd post it here in case anyone else finds it useful.

<?php

/*
 *    Function to calculate which days are British bank holidays (England & Wales) for a given year.
 *
 *    Created by David Scourfield, 07 August 2006, and released into the public domain.
 *    Anybody may use and/or modify this code.
 *
 *    USAGE:
 *
 *    array calculateBankHolidays(int $yr)
 *
 *    ARGUMENTS
 *
 *    $yr = 4 digit numeric representation of the year (eg 1997).
 *
 *    RETURN VALUE
 *
 *    Returns an array of strings where each string is a date of a bank holiday in the format "yyyy-mm-dd".
 *
 *    See example below
 *
 */

function calculateBankHolidays($yr) {

   
$bankHols = Array();

   
// New year's:
   
switch ( date("w", strtotime("$yr-01-01 12:00:00")) ) {
        case
6:
           
$bankHols[] = "$yr-01-03";
            break;
        case
0:
           
$bankHols[] = "$yr-01-02";
            break;
        default:
           
$bankHols[] = "$yr-01-01";
    }

   
// Good friday:
   
$bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) - 2)." days", strtotime("$yr-03-21 12:00:00") ));

   
// Easter Monday:
   
$bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) + 1)." days", strtotime("$yr-03-21 12:00:00") ));

   
// May Day:
   
if ($yr == 1995) {
       
$bankHols[] = "1995-05-08"; // VE day 50th anniversary year exception
   
} else {
        switch (
date("w", strtotime("$yr-05-01 12:00:00"))) {
            case
0:
               
$bankHols[] = "$yr-05-02";
                break;
            case
1:
               
$bankHols[] = "$yr-05-01";
                break;
            case
2:
               
$bankHols[] = "$yr-05-07";
                break;
            case
3:
               
$bankHols[] = "$yr-05-06";
                break;
            case
4:
               
$bankHols[] = "$yr-05-05";
                break;
            case
5:
               
$bankHols[] = "$yr-05-04";
                break;
            case
6:
               
$bankHols[] = "$yr-05-03";
                break;
        }
    }

   
// Whitsun:
   
if ($yr == 2002) { // exception year
       
$bankHols[] = "2002-06-03";
       
$bankHols[] = "2002-06-04";
    } else {
        switch (
date("w", strtotime("$yr-05-31 12:00:00"))) {
            case
0:
               
$bankHols[] = "$yr-05-25";
                break;
            case
1:
               
$bankHols[] = "$yr-05-31";
                break;
            case
2:
               
$bankHols[] = "$yr-05-30";
                break;
            case
3:
               
$bankHols[] = "$yr-05-29";
                break;
            case
4:
               
$bankHols[] = "$yr-05-28";
                break;
            case
5:
               
$bankHols[] = "$yr-05-27";
                break;
            case
6:
               
$bankHols[] = "$yr-05-26";
                break;
        }
    }

   
// Summer Bank Holiday:
   
switch (date("w", strtotime("$yr-08-31 12:00:00"))) {
        case
0:
           
$bankHols[] = "$yr-08-25";
            break;
        case
1:
           
$bankHols[] = "$yr-08-31";
            break;
        case
2:
           
$bankHols[] = "$yr-08-30";
            break;
        case
3:
           
$bankHols[] = "$yr-08-29";
            break;
        case
4:
           
$bankHols[] = "$yr-08-28";
            break;
        case
5:
           
$bankHols[] = "$yr-08-27";
            break;
        case
6:
           
$bankHols[] = "$yr-08-26";
            break;
    }

   
// Christmas:
   
switch ( date("w", strtotime("$yr-12-25 12:00:00")) ) {
        case
5:
           
$bankHols[] = "$yr-12-25";
           
$bankHols[] = "$yr-12-28";
            break;
        case
6:
           
$bankHols[] = "$yr-12-27";
           
$bankHols[] = "$yr-12-28";
            break;
        case
0:
           
$bankHols[] = "$yr-12-26";
           
$bankHols[] = "$yr-12-27";
            break;
        default:
           
$bankHols[] = "$yr-12-25";
           
$bankHols[] = "$yr-12-26";
    }

   
// Millenium eve
   
if ($yr == 1999) {
       
$bankHols[] = "1999-12-31";
    }

    return
$bankHols;

}

/*
 *    EXAMPLE:
 *
 */

header("Content-type: text/plain");

$bankHolsThisYear = calculateBankHolidays(2007);

print_r($bankHolsThisYear);

?>

Will output this result:

Array
(
    [0] => 2007-01-01
    [1] => 2007-04-06
    [2] => 2007-04-09
    [3] => 2007-05-07
    [4] => 2007-05-28
    [5] => 2007-08-27
    [6] => 2007-12-25
    [7] => 2007-12-26
)
ben78
12-Aug-2007 04:00
Find on the web.

Diff between date seconds, minutes, hours, month, days and years!

Very usefull and so simple :-)

$d1=mktime(22,0,0,1,1,2007);
$d2=mktime(0,0,0,1,2,2007);
echo "Hours difference = ".floor(($d2-$d1)/3600) . "<br>";
echo "Minutes difference = ".floor(($d2-$d1)/60) . "<br>";
echo "Seconds difference = " .($d2-$d1). "<br>";

echo "Month difference = ".floor(($d2-$d1)/2628000) . "<br>";
echo "Days difference = ".floor(($d2-$d1)/86400) . "<br>";
echo "Year difference = ".floor(($d2-$d1)/31536000) . "<br>";
jasonlfunk (at) gmail dot com
10-Aug-2007 12:39
If there is an easier way to find the week of the month, let me know. Here is how I figured out how to do it;

date("W") - date("W",strtotime(date("F") . " 1st " . date("Y"))) + 1;
Robert
08-Aug-2007 08:49
This will show the day (Monday, Tuesday, etc) for any given date.

<?php
$mon
= 12;
$day = 31;
$year = 1980;
$stamp = mktime(0,0,0,$mon,$day,$year);

echo
date('l',$stamp);
?>
me at stewartkirkpatrick dot com
29-Jul-2007 06:54
This will calculate the 'SPOT' date for FX trades (two working days hence)

<?php

// get the day
$d=date("D");

// if today is Thu or Friday add 4 days to today
if ($d=="Thu" || $d=="Fri") {
$spot  = time() + (4 * 24 * 60 * 60);
echo
"<p>";
echo
date("d/m/Y", $spot);
echo
"</p>";
}

// else just add two days to today
else {
$spot  = time() + (2 * 24 * 60 * 60);
echo
"<p>";
echo
date("d/m/Y", $spot);
echo
"</p>";
}
?>
luis dot sv at gmail dot com
20-Jul-2007 11:00
In relation to soreenpk at yahoo dot com's message:

That code doesn't work for two dates with a difference larger than a year, for example:
$digest_date = "2006-04-14";
$date2="2007-04-15";
$date_diff = date("d",strtotime($date2)) - date("d",strtotime($digest_date));//$date_diff = 1
dwdaddhp at yahoo dot de
19-Jul-2007 12:55
<?php
function isago($hour, $min){
$difference=($hour*60+$min)-(date("H")*60+date("i"));
if(
$difference<=0)
return
true;
else if(
$difference>0)
return
false;   
}

if(
isago(20,0))
echo
"after eight";
else
echo
"befor eight";
?>
ThomasEdison
18-Jul-2007 03:16
This function is like date, but it "speaks" Hungarian (or an other language)

<?php
/*
  these are the hungarian additional format characters
 
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571