티스토리 뷰

Server Side Script/PHP

PHP date

미련곰 2007. 8. 20. 14:07
 

date

(PHP 3, PHP 4 , PHP 5)

date -- 로컬 날짜/시간을 형식화합니다.

설명

string date ( string format [, int timestamp])

정수형으로 주어지는 timestamp나, timestamp가 주어지지 않았을 경우에는 현재 로컬 시간을 사용하여, 주어진 포맷 문자열에 따라 형식화한 문자열을 반환합니다. 즉 timestamp는 선택적이고, 기본값은 time()의 값입니다.

참고: 전형적인 timestamp의 유효 범위는 1901년 12월 13일 금요일 20:45:54 GMT부터 2038년 1월 19일 화요일 03:14:07 GMT입니다. (이것은 부호 있는 32비트 정수형의 최소와 최대값에 대응합니다. 윈도우즈에서는 이 값은 1970-01-01부터 2038-01-19로 제한됩니다)

참고: 날짜를 표시하는 문자열로부터 timestamp를 생성하기 위해서, strtotime()을 사용할 수 있습니다. 또한, 몇몇 데이터베이스는 각자의 날짜 형식으로에서 timestamp로 변환하는 함수를 가지고 있습니다. (예: MySQL의 UNIX_TIMESTAMP 함수)

표 1. 다음 문자들은 format 인자 문자열로 인식합니다.

format 문자 설명 반환값 예
a 오전과 오후, 소문자 am, pm
A 오전과 오후, 대문자 AM, PM
B 스왓치 인터넷 시간 000부터 999
c ISO 8601 날짜 (PHP 5에서 추가) 2004-02-12T15:19:21+00:00
d 일, 앞에 0이 붙는 2자리 01부터 31
D 요일, 3글자 문자 Mon부터 Sun
F 월, January, March 등의 완전한 문자 표현 January부터 December
g 시, 0이 붙지 않는 12시간 형식 1부터 12
G 시, 0이 붙지 않는 24시간 형식 0부터 23
h 시, 0이 붙는 12시간 형식 01부터 12
H 시, 0이 붙는 24시간 형식 00부터 23
i 분, 0이 붙는 형식 00부터 59
I (대문자 i) 일광 절약 시간 여부 일광 절약 시간이면 1, 아니면 0
j 일, 0이 붙지 않는 형식 1부터 31
l (소문자 'L') 요일, 완전한 문자 표현 Sunday부터 Saturday
L 윤년인지 여부 윤년이면 1, 아니면 0
m 월, 숫자 표현, 0이 붙는 형식 01부터 12
M 월, 짧은 문자 표현, 3문자 Jan부터 Dec
n 월, 숫자 표현, 0이 붙지 않는 형식 1부터 12
O 그리니치 시간(GMT)과의 차이 예: +0200
r RFC 2822 형식 날짜 예: Thu, 21 Dec 2000 16:01:07 +0200
s 초, 0이 붙는 형식 00 부터 59
S 일 표현을 위한 영어 서수 접미어, 2문자 st, nd, rdth. j와 잘 작동합니다.
t 주어진 월의 일수 28부터 31
T 이 기계의 표준 시간대 설정 예: EST, MDT ...
U 유닉스 Epoch(January 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 형식은 gmdate()를 이용할 때는 항상 0을 반환합니다.

예 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
));
?>

format 문자열로 인식하는 문자 바로 앞에 백슬래쉬를 붙여서 이스케이프를 함으로써, 인식하는 것 막을 수 있습니다. 백슬래쉬가 붙는 문자가 이미 특별한 의미를 가지고 있다면, 백슬래쉬를 이스케이프해야 합니다.

예 2. date()의 회피 문자

<?php
// 다음의 출력: Wednesday the 15th
echo date("l \\t\h\e jS"
);
?>

date()mktime()을 함께 사용함으로써 미래나 과거의 시간을 얻을 수 있습니다.

예 3. date()mktime() 예제코드

<?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
);
?>

참고: 이는 일광 절약 시간을 고려하기 때문에, 단순히 timestamp에 하루나 한달에 해당하는 초를 더하는 것보다 신뢰할 수 있습니다.

date() 형식화의 몇몇 예제. 모든 다른 문자들도 이스케이프 해야함에 주의하십시오. 현재 특별한 의미를 가진 어떤 것이 바람직하지 못한 결과를 가져올 수 있고, 앞으로의 PHP 버전에서는 다른 문자들도 지정될 수가 있습니다. 이스케이프 할 때는, \n이 줄바꿈으로 인식 되는 것과 같은 예을 피하기 위해서는 작은 따옴표를 사용해야만 합니다.

예 4. date() 형식화

<?php
// Assuming today is: 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().



add a note add a note User Contributed Notes
date
flammie at iki dot fi
17-Dec-2005 09:27
It seems, that using date("B") in some PHP 5.1.1 can result in "[B unimplemented]". This can be very ungood, if you had previously used B to get uniquish but readable timestamps for eg. filenames. Fortunately in new PHP it can be replaced with "IH", for older PHP's forcing UTC timezone would be the way to go.
ian_freeworld at yahoo dot com
16-Dec-2005 04:39
to calculate how many days from this day to the date before

<?
// example you want to calculate date between now and December 12, 2005

$day_now=date("j"
);
$month_now=date("n"
);
$year_now=date("Y"
);

$date_now=date("z", mktime(0, 0, 0, $month_now, $day_now, $year_now
));

$day_before=12
;
$month_before=12
;
$year_before=2005
;

$date_before=date("z", mktime(0, 0, 0, $month_before, $day_before, $year_before
));

$calculate=$date_now-$date_before
;

echo
$calculate
;

?>
hope it's worth..
thanks..

Younk's
Indonesia
djwood at gmail dot com
15-Dec-2005 08:32
I've found these user entries so useful over time, I finally decided to return the favor. Hopefully this helps someone.

I searched for this for a while. I was trying to figure out how many days elapsed between two dates, or in other words the difference between two dates. I set it up in PHP with some other users suggestions:

$init_date = mktime(12,0,0,$arrival_month,$arrival_day,$arrival_year);

$dst_date = mktime(12,0,0,$departure_month,$departure_day,$departure_year);

$offset = $dst_date-$init_date;
$days_elapsed = floor($offset/86400);

It worked ok, except I noticed it had some trouble if you were spanning months, (i.e. 03-29-2005 to 04-10-2005) it would sometimes count one less than the actual elapsed days. So obviously this is not good.

IF YOU HAVE ACCESS TO A MYSQL DATABASE:

I found this to be the easiest and most accurate way:
----------------------------------------------------------
$elapsed_query = mysql_query("SELECT to_days( '$depart' ) - to_days( '$arrive' ) AS days_elapsed")or die("Query failed");

$days_elapsed = mysql_result($elapsed_query, 0, 0);

---------------------------------------------------------
It's working great for me, I hope this helps someone.
ihr at rafft-es-einfach dot net
15-Dec-2005 09:38
A function to return an array ($week) containing the first second of the the week (["begin"]) and the last second of the week (["end"]).
NOTE:
1. I haven't tested it on ALL dates yet, but it should act sane anyay.
2. THIS SCRIPT IS NOT COPYRIGHTED IN ANY FORM.

<?php

$current_week
=get_week_boundaries($time
());
$the_next_sunday=$current_week["end"
];
$the_last_monday=$current_week["begin"
];
$now=$current_week["pov"
];

function
get_week_boundaries($int_time
) {
//first: find monday 0:00
$weekdayid=date("w",$int_time
);
$dayid=date("j",$int_time
);
$monthid=date("n", $int_time
);
$yearid=date("Y", $int_time
);
$beginofday=mktime(0,0,0,$monthid,$dayid,$yearid
);
$beginofweek=$beginofday - (($weekdayid-1) * 86400);
//86400 == seconds of one day (24 hours)
//now add the value of one week and call it the end of the week
//NOTE: End of week is Sunday, 23:59:59. I think you could also use Monday 00:00:00 but I though that'd suck
$endofweek=($beginofweek + 7 * 86400)-1
;
$week["begin"]=$beginofweek
;
$week["end"]=$endofweek
;
$week["pov"]=$int_time
;
return
$week
;
}
?>
KED
14-Dec-2005 08:32
Why not just:

function next_month($m, $y)
{if(++$m > 12) {$m = 1; ++$y;}
 return array($m, $y);
}

function previous_month($m, $y)
{if(--$m < 1) {$m = 12; --$y;}
 return array($m, $y);
}
admin at epark dot pl
14-Dec-2005 01:43
here a little two functions for rewind the month in for example calendar
I couldn't find it anywhere, maybe sombody need it
peace :)

     function next_month($m, $y)
     {
               if ($m%12==0)
               {
               $mi_n=$m-11;
               $ye_n=$y+01;
               }
               else       
               {
               $mi_n=$m+1;
               $ye_n=$y;
               }
     return $m;
     return $y;
     }
  
     function previous_month($m,$y)
     {
               if (($m-1)%12==0)
               {
               $mi_p=$m+11;
               $ye_p=$y-01;
               }
               else       
               {
               $mi_p=$m-1;
               $ye_p=$y;
               }
   return $m;
   return $y;
     }
abu_aaminah at yahoo dot co dot uk
14-Dec-2005 12:38
My function (http://phpshortcuts.blog-city.com/dateconvert_1.htm
) for converting system dates into user-friendly dates depending on the scenario in which it's used:

<?
function DateConvert($old_date, $layout
)
{
//Remove non-numeric characters that might exist (e.g. hyphens and colons)
$old_date = ereg_replace('[^0-9]', '', $old_date
);

//Extract the different elements that make up the date and time
$_year = substr($old_date,0,4
);
$_month = substr($old_date,5,2
);
$_day = substr($old_date,8,2
);
$_hour = substr($old_date,11,2
);
$_minute = substr($old_date,14,2
);
$_second = substr($old_date,17,2
);

//Combine the date function with mktime to produce a user-friendly date & time
$new_date = date($layout, mktime($_hour, $_minute, $_second, $_month, $_day, $_year
));
return
$new_date
;
}
?>

The function is then called like this:

<?
$todays_date
= "2005-07-01 12:35:01"
;

//We can use words to desccribe the date (as you see on on my blog)
print DateConvert($todays_date, "l, jS F Y");
//Friday, 1st July 2005

//We can use the UK style
print DateConvert($todays_date, "d/m/Y");
//01/07/2005

//We can use the US style
print DateConvert($todays_date, "Y/m/d");
//2005/07/01

//We can even add the time
print DateConvert($todays_date, "Y/m/d - g:ia");
//2005/07/01 12:35pm
?>
garis at intec dot edu dot do
28-Nov-2005 09:46
To print a drop down box, with the next three years:
can be used for days, months, etc. or any other value you want to print a lot of values... there is just the concept
<select name="year">
<option selected>YEAR</option>
<?php
   $year
= date('Y'
);
  
$itmp = $year+3
;
   for (
$i=$year; $i <= $itmp; $i
++) {
      
printf('<option value=\''.$i.'\'>'.$i.'</option>'
);
   }
 
?>
</select>
chetan at jethwa dot org
25-Nov-2005 11:17
function for calculating N working days from a date.

<?php
/*
$date - date (dd/mm/yyyy)
$n - number of days
$t - resulting timestamp
*/

function getNthWorkingDay($date,$n,&$t
)
{
  
$arr
= array();
   list(
$day,$month,$year) = explode("/",$date
);

  
$ts = mktime(0,0,0,$month,$day,$year
);

   for(
$i = 1; $i <= $n; $i
++)
   {
      
$_ts = mktime(0,0,0,$month,$day + $i,$year
);
      
$arr[$i - 1]["d"] = date("w",$_ts
);
      
$arr[$i - 1]["ts"] = $_ts
;
   }

  
$working_days
= array();
  
$j = 0
;

   for(
$i = 1; $i <= $n; $i
++)
   {
       if(
$arr[$i - 1]["d"] != 6 AND $arr[$i - 1]["d"] != 0
)
       {
          
$working_days[$j]["d"] = $arr[$i - 1]["d"
];
          
$working_days[$j]["ts"] = $arr[$i - 1]["ts"
];
          
$j
++;
       }
   }

   if(
sizeOf($working_days) >= $n
)
   {
      
$t = $working_days[sizeOf($working_days) - 1]["ts"
];
   }
   else
   {
      
$_n = $n - sizeOf($working_days
);
      
      
getNthWorkingDay(date("d/m/Y",$arr[$n-1]["ts"]),$_n,$t
);
   }
}
?>
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
kroni at onetel dot com
24-Nov-2005 12:30
A remark to the findWeekPeriod function by
leonardo at kreativ dot ro:
This function only works correctly for 2005!!!

See end of the
http://www.phpbuilder.com/board/showthread.php?t=10222903
article for code which works for all years
wilhelm dot moser at demos dot at
23-Nov-2005 11:59
function DayDiff($StartDate, $StopDate)
{
   // converting the dates to epoch and dividing the difference
   // to the approriate days using 86400 seconds for a day
   //
   return (date('U', strtotime($StopDate)) - date('U', strtotime($StartDate))) / 86400; //seconds a day
}
php at radio-network dot de
19-Nov-2005 01:51
Here you have final functions for date and timestamp formatting!
Date formatting is german - you may change it !

function stamp2date($stamp){        // expects a valid timestamp
   return date("d.m.Y", $stamp);    // returns 19.11.2005
}

function date2stamp($date){        // format: 19.11.2005
   $tmp = explode(".", $date);   
   return mktime(0,0,0,$tmp[1], $tmp[0], $tmp[2]);
}

Tweak it for yourself! But these vice-versa functions will help you a lot with handling dates on databases <> forms
itsacon at itsacon dot net
16-Nov-2005 10:28
Caveat when using the 'W' and 'w' options together:

The 'W' option uses the ISO-8601 standard (week ends on sunday), whereas the 'w' option has the week _start_ on sunday (sunday == 0).
Jay J
11-Nov-2005 05:13
I use 14 character long datetime fields (20050905105237) in my database. I needed a way to easily transform them into human-readable format so I wrote the mydate() function.

<?

$datetime
= "20050905105237"
;
$justdate = "20050905"
;

echo
mydate("Y-m-d H:i:s", $datetime
);
// Produces 2005-09-05 10:52:37

echo mydate("l, F j, Y", $justdate
);
// Produces Monday, September 5, 2005

function mydate($format, $publictime
)
{
      
$sec = substr($publictime, 12, 2
);
      
$min = substr($publictime, 10, 2
);
      
$hour = substr($publictime, 8, 2
);
      
$day = substr($publictime, 6, 2
);
      
$month = substr($publictime, 4, 2
);
      
$year = substr($publictime, 0, 4
);
       return
date($format, mktime($hour, $min, $sec, $month, $day, $year
));
}

?>
fab097 at gmail dot com
05-Nov-2005 06:59
if you use mySQL "YEARWEEK" function, you may need to compute YearWeek in PHP...
with date("YW",$date) you will have trouble because week number may overflow year, and the "Y" is not synchronized.

for example, 30th december of year 2003. is the 1st week of year 2004.
date("YW",$date) gives wrongly "200301" !
then you better use date("oW",$date) that gives you "200401".
leonardo at kreativ dot ro
04-Nov-2005 12:04
If you want to find the corresponding starting and ending dates for a given week of a year:

function findWeekPeriod($week, $year)
{
   $aPeriod = array();

   // if you are a Catholic you should use $x = 0 considering Sunday as the first day of the week. I'm an Orthodox so I consider it the seventh day of the week

   $x = 1;

   $aPeriod['start'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1 + $week*7 + $x - 6, $year));

   $aPeriod['end'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1 + $week*7 + $x, $year));

   return $aPeriod;
}

For week 44 of the year 2005 (as an example), you will get:

Array ( [start] => 2005-10-31 00:00:00 [end] => 2005-11-06 00:00:00 )
michael at bluth-company dot com
03-Nov-2005 02:06
A possible correction on the GMT Time Magic function. When you get the Time Offset you just got the current offset but you actually need to get the offset corresponding to the *timestamp*.

I changed date("Z") into date("Z",$Stamp);

# ~~~ GMT Time Magic v2.0 ~~~~~~~~~~ #
function GMT_Time($Stamp) {
   return (($Stamp == 0) ? time() : $Stamp) + date("Z",$Stamp);
}

Thats how it worked for me.
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
);
?>
jazzle
02-Nov-2005 10:01
Remember, if you want to include a special character such as '?' (·) within a date() call you must escape every letter of the code.
For example
date('Y-m-d\&\m\i\d\d\o\t\;H:i:s')
will output
2005-11-02?11:54:42
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
eddielien
28-Oct-2005 07:56
I tried this function on Redhat AS4, and I found the date function returned hwclock time, instead of system time. So guys who are using this function on time serious projects should always keep hwclock time sync to system time.
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.
paulhan at eircom dot net
24-Oct-2005 08:03
Same day in week each month script
This is a script I use to find dates based on first or third  Friday in every month (or any other day in a month)
<?php
//For this example, give nextdate a timestamp
$nextdate = time
();
//Format nextdate for viewing
$output = date("D d-F-Y H:i", $nextdate)."<br />\n"
;
//Initialise no of days in month array
$monArr=array(31,28,31,30,31,30,31,31,30,31,30,31
);
//Get the next twelve months (can be more or less)
for ($i=0; $i<12; $i
++){
  
//Convert timestamp into its constituents
  
$dt = getdate($nextdate
);
  
//Get no of days in the month
  
$nod = $monArr[$dt['mon']-1
];
  
//Do a simple leap year check. Better example elsewhere
  
if ($dt['mon']==2 && ($dt['year']%4) == 0
){
      
$nod = 29
;
   }
  
//Get the day part of the time
  
$dom = $dt['mday'
];
  
//Get earliest possible date for that day
  
$firstday = $dom % 7
;
  
//Get the difference between the number of days and the
   // maximum number of possible weeks in a month
  
$diff = $nod - 28
;
  
//If the earliest possible date falls within that difference
   // and is greater than 0, and the date is less than 28,
   // then add 35 days using strtotime to get over DST
   //issues. Just means there will be five of those days in
   // the month
  
if ($firstday <= $diff && $firstday > 0 && $dom < 28
){
      
$nextdate = strtotime("+35 days",$nextdate
);
  
//If not, just add 28 days to the date
  
}else{
  
$nextdate = strtotime("+28 days",$nextdate
);
   }
  
//Show the output for checking, could also use the raw
   // timestamp for a mysql query
  
$output .= date("D d-F-Y H:i", $nextdate)."<br />\n"
;
  
//Should output the third Friday in every month, for
   // instance
  
echo $output
;
}

?>
Chris McKee
21-Oct-2005 03:03
<?php
/**
* function dateconvert
*
* dateconvert is a handy function to take the aches and pains out of mysqls stupidity
* by converting data from a variable (posted from a form or just stored)
* into a format mysql will be able to store and converting the
* database date back into the british standard of date month year.
* The Script accepts day.month.year or day/month/year or day-month-year.
* example:
*
* <code>
* <?php  // using type 1
*    $date = "19.12.2005";
*    $date = dateconvert($date, 1);
*    echo $date;  // Would echo 2005-12-19 which is the format stored by mysql
* ?>
* </code>
* <code>
* <?php  // using type 2
*    $date = $row['date']; //your mysql date
*    $realdate = dateconvert($date,2);
*    echo $realdate; // would display 19/12/2005
*    ?>
* </code>
*
* @author Chris McKee <pcdevils@gmail.com> 
*
* @param  string $date - Date to be converted
* @param  string $func - which function is to be used (1 for input to mysql, 2 for output from mysql)
*/

function dateconvert($date,$func
) {
       if (
$func == 1){
//insert conversion
          
list($day, $month, $year) = split('[/.-]', $date
);
          
$date = "$year-$month-$day"
;
           return
$date
;
       }
       if (
$func == 2){
//output conversion
          
list($year, $month, $day) = split('[-.]', $date
);
          
$date = "$day/$month/$year"
;
           return
$date
;
       }
      
}
?>
jbricci at ya-right dot net
16-Oct-2005 05:13
date function for windows supporting dates before 1-1-1970

usage....

negtime2date ( date_format, time_stamp, off_set );

if no off_set is passed or off_set = 0, gmdate for the timestamp is returned. Other wise the date formatted is based on the off_set

see my function under * gmmktime * for a example on how to create negative timestamps (dates before 1-1-1970)

<?

// usage...

echo negtime2date ( 'D, F d, Y H:i:s A', -1514196929, -5 );
// Jan 7, 1922 - 13:44:31 PM GMT

function negtime2date ( $tf, $ts, $to = 0
)
{
  
$ta = array ( 60, 3600, 86400, 365
);
  
$ts += ( $to * $ta[1
] );

   if (
$ts < 0
)
   {
      
$i = 11
;
      
$ad = 0
;
      
$wd = 3
;
      
$od = $ta[3
];
      
$tt = $to[0
];
      
$to = substr( $to, 1
);
      
$mm = '00'
;

       if (
strpos ( $to, '.'
) )
       {
          
$am = array ( 5 => 30, 25 => 15, 75 => 45
);
          
$tp = explode ( '.', $to
);
          
$to = $tp[0
];
          
$mm = isset ( $am[$tp[1]] ) ? $am[$tp[1]] : '00'
;
       }

      
$ap = array ( 'am', 'AM', 'pm', 'PM'
);
      
$sd = array ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
);
      
$ld = array ( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
);
      
$sm = array ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
);
      
$lm = array ( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'
);
      
$oa = array ( 0, 0, 0, 12, 0, 1969
);
      
$ma = array ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
);

       while (
$ts < ( -( $ta[3] + $ad ) * $ta[2
] ) )
       {
          
$ad = 0
;
          
$td = 1
;
          
$ma[1] = 28
;

           if ( (
$oa[5] % 4 ) == 0 && ( $oa[5] % 100 > 0 || $oa[5] % 400 == 0
) )
           {
              
$ad = 1
;
              
$td = 2
;
              
$ma[1] = 29
;
           }

           while (
$td
-- )
           {
              
$wd = $wd ? $wd : 7
;
              
$wd
--;
              
$wd = ! $wd && $td ? 7 : $wd
;
           }

          
$ts += ( $ta[3] + $ad ) * $ta[2
];
          
$oa[5] -= 1
;
       }

      
$od += $ad
;

       while (
$ts < ( -$ma[$i] * $ta[2
] ) )
       {
          
$ts += ( $ma[$i] * $ta[2
] );
          
$oa[3] -= 1
;
          
$od -= $ma[$i
];
          
$td = ( $ma[$i] - 28
);

           while (
$td
-- )
           {
              
$wd = $wd ? $wd : 7
;
              
$wd
--;
              
$wd = ! $wd && $td ? 7 : $wd
;
           }

          
$i
--;
       }

      
$oa[4] = ( $ma[$i] + ceil ( ( $ts + 1 ) / $ta[2
] ) );
      
$td = ( $ma[$i] - $oa[4
] );

       while (
$td
-- )
       {
          
$wd = $wd ? $wd : 7
;
          
$wd
--;
          
$wd = ! $wd && $td ? 7 : $wd
;
          
$od -= 1
;
       }

      
$ts += ( ( $ma[$i] - $oa[4] + 1 ) * $ta[2
] );
      
$oa[0] = floor ( $ts / $ta[1
] );
      
$ts -= ( $oa[0] * $ta[1
] );
      
$oa[1] = floor ( $ts / $ta[0
] );
      
$oa[2] = ( $ts - $oa[1] * $ta[0
] );

      
$new
= array (
      
'z' => ( $od ? ( $od - 1 ) : 0
),
      
'W' => ( $od <= 7 ? 1 : round ( $od / 7
) ),
      
's' => sprintf ( '%02s', $oa[2
] ),
      
'i' => sprintf ( '%02s', $oa[1
] ),
      
'g' => ( $oa[0] > 12 ? ( $oa[0] - 12 ) : $oa[0
] ),
      
'G' => $oa[0
],
      
'h' => sprintf ( '%02s', ( $oa[0] > 12 ? ( $oa[0] - 12 ) : $oa[0
] ) ),
      
'H' => sprintf ( '%02s', $oa[0
] ),
      
't' => $ma[$i
],
      
'L' => ( 29 - $ma[1
] ),
      
'w' => $wd
,
      
'N' => ( 1 + $wd
),
      
'm' => sprintf ( '%02s', $oa[3
] ),
      
'n' => $oa[3
],
      
'd' => sprintf ( '%02s', $oa[4
] ),
      
'y' => substr ( $oa[5], 2
),
      
'Y' => $oa[5
],
      
'j' => $oa[4
],
      
'S' => ( ( $s = substr ( $oa[4], - 1 ) ) == 1 ? 'st' : ( $s == 2 ? 'nd' : ( $s == 3 ? 'rd' : 'th'
) ) ),
      
'F' => $lm[$i
],
      
'M' => $sm[$i
],
      
'D' => $sd[$wd
],
      
'l' => $ld[$wd
],
      
'a' => ( $oa[0] >= 12 ? $ap[2] : $ap[0
] ),
      
'A' => ( $oa[0] >= 12 ? $ap[3] : $ap[1
] ),
      
'O' => sprintf ( $tt . '%02s' . $mm, $to
),
      
'Z' => ( ( $tt == '-' ? $tt : null ) . ( ( $to * $ta[1] ) + ( $mm * $ta[0
] ) ) ),
      
'c' => sprintf ( $oa[5] . '-%02s-%02sT%02s:%02s:%02s' . $tt . '%02s:' . $mm, $oa[3], $oa[4], $oa[0], $oa[1], $oa[2], $to
),
      
'r' => sprintf ( $sd[$wd] . ', %02s ' . $sm[$i] . ' ' . $oa[5] . ' %02s:%02s:%02s ' . $tt . '%02s' . $mm, $oa[4], $oa[0], $oa[1], $oa[2], $to
) );

       return (
strtr ( $tf, $new
) );
   }
   else
   {
       return (
gmdate ( $tf, $ts
) );
   }
}
?>
mendoza at pvv dot ntnu dot no
13-Oct-2005 05:38
At "daykay at pdsoftware dot de":

09 != 9 so there's nothing wrong about European vs. American formats.

$ php -r 'print 09; print "\n"; print 9; print "\n";'
0
9

09 is treated as octal and since octal numbers only use the 0-7 digits, it evaluates to 0. All numbers prefixed with 0 are considered octal just as 0x are considered hexadecimal.

http://en.wikipedia.org/wiki/Computer_numbering_formats
jim at catsanddogs dot com
12-Oct-2005 10:52
To get the start date for a working week:

<?php

list($iDay, $iMonth, $iYear) = split('-', date('d-m-Y', mktime(0, 0, 0, date('n'), ((date('j')+1)-date('w')), date('Y'
))));

return
$iDay.'-'.$iMonth.'-'.$iYear
;

?>
manuel
10-Oct-2005 12:55
Retunrs Timestamp of first Saturady of a given month and year.

function getfirstSaturday ($mon,$year) {
  $timegiven = mktime (0,0,0,$mon,1,$year);
  $mon = date('n',$timegiven);
  $year = date('Y',$timegiven);
  $day = 1 + ( 6 - date('w',$timegiven) );
  return ( mktime(0,0,0,$mon,$day,$year) );
}

echo date('d.m.Y', getfirstSaturday (12,2005) );
// Return: 03.12.2005
DueJogn at Gmail dot com
08-Oct-2005 11:44
<?php
  
/*
   a simple date function witch turns an english date syntax into a hebrew syntax something like this:
   Before:Saturday 08th of October 2005 15:26
   After:יום שבת ה08 לאוקטובר 2005 15:26
   */
  
function date2heb
()
   {
      
$eng_date = date("l dS \of F Y H:i");
#getting date with syntax: Saturday 08th of October 2005 15:01
      
$eng_date_array = explode(" ",$eng_date);
#arraying the date for a cormftuble use
       #Renaming the date array
      
$eng_date_array['week_day'] = $eng_date_array[0]; unset($eng_date_array[0
]);
      
$eng_date_array['num'] = $eng_date_array[1]; unset($eng_date_array[1
]);
      
$eng_date_array['of'] = $eng_date_array[2]; unset($eng_date_array[2
]);
      
$eng_date_array['month'] = $eng_date_array[3]; unset($eng_date_array[3
]);
      
$eng_date_array['year'] = $eng_date_array[4]; unset($eng_date_array[4
]);
      
$eng_date_array['time'] = $eng_date_array[5]; unset($eng_date_array[5
]);
      
#loading the names of the motnth and dayes into an array
      
$heb_date_array_db
= array(
          
'month'
=> array(
              
'January' => "ינואר"
,
              
'February' => "פברואר"
,
              
'March' => "מרס"
,
              
'April' => "אפריל"
,
              
'May' => "מאי"
,
              
'June' => "יוני"
,
              
'July' => "יולי"
,
              
'August' => "אוגוסט"
,
              
'September' => "ספטמבר"
,
              
'October' => "אוקטובר"
,
              
'November' => "נובמבר"
,
              
'December' => "דצמבר"
,
           ),
          
          
'week_day'
=> array(
              
'Sunday' => "ראשון"
,
              
'Monday' => "שני"
,
              
'Tuesday' => "שלישי"
,
              
'Wednesday' => "רבעי"
,
              
'Thursday' => "חמישי"
,
              
'Friday' => "שישי"
,
              
'Saturday' => "שבת"
,
           ),
       );
      
#replacing with hebrew
      
foreach($heb_date_array_db['week_day'] as $eng_week_day => $heb_week_day
)
           if(
$eng_week_day == $eng_date_array['week_day'
])
              
$heb_date_array['week_day'] = "יום " . $heb_week_day . " "
;
              
      
$heb_date_array['num'] = str_replace("th","",$eng_date_array['num'
]);
      
$heb_date_array['num'] = "ה" . $heb_date_array['num'] . " "
;
      
$heb_date_array['of'] = "ל"
;
      
       foreach(
$heb_date_array_db['month'] as $eng_month => $heb_month
)
           if(
$eng_month == $eng_date_array['month'
])
              
$heb_date_array['month'] = $heb_month . " "
;
              
      
$heb_date_array['year'] = $eng_date_array['year'] . " "
;
      
$heb_date_array['time'] = $eng_date_array['time'] . " "
;
      
      
$heb_date = implode("",$heb_date_array);
#having the date imploded
      
return $heb_date
;
      
#cheers! leon
  
}
  
   echo
date2heb
();
?>
rubyip at gmail dot com
05-Oct-2005 06:30
just modified the function posted here... i forgot the name of the original author...

<?php
//date difference function
function datediff($interval, $date1, $date2
) {
  
// Function roughly equivalent to the ASP "DateDiff" function
  
   //convert the dates into timestamps
 
$date1 = strtotime($date1
);
 
$date2 = strtotime($date2
); 
 
$seconds = $date2 - $date1
;
 
  
//if $date1 > $date2
   //change substraction order
   //convert the diff to +ve integer
  
if ($seconds < 0
)
   {
          
$tmp = $date1
;
          
$date1 = $date2
;
          
$date2 = $tmp
;
          
$seconds = 0-$seconds
;           
   }
  
  
//reconvert the timestamps into dates
  
if ($interval =='y' || $interval=='m'
) {
      
$date1 = date("Y-m-d h:i:s", $date1
);
      
$date2date("Y-m-d h:i:s", $date2
);         
   }
  
   switch(
$interval
) {
       case
"y"
:
           list(
$year1, $month1, $day1) = split('-', $date1
);
           list(
$year2, $month2, $day2) = split('-', $date2
);
          
$time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1
));
          
$time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2
));
          
$diff = $year2 - $year1
;
          
           if(
$month1 > $month2
) {
              
$diff -= 1
;
           } elseif(
$month1 == $month2
) {
               if(
$day1 > $day2
) {
                  
$diff -= 1
;
               } elseif(
$day1 == $day2
) {
                   if(
$time1 > $time2
) {
                      
$diff -= 1
;
                   }
               }
           }
           break;
       case
"m"
:     
           list(
$year1, $month1, $day1) = split('-', $date1
);
           list(
$year2, $month2, $day2) = split('-',$date2
);
          
$time1 = (date('H',$date1)*3600) + (date('i',$date1)*60) + (date('s',$date1
));
          
$time2 = (date('H',$date2)*3600) + (date('i',$date2)*60) + (date('s',$date2
));
          
$diff = ($year2 * 12 + $month2) - ($year1 * 12 + $month1
);
           if(
$day1 > $day2
) {
              
$diff -= 1
;
           } elseif(
$day1 == $day2
) {
               if(
$time1 > $time2
) {
                  
$diff -= 1
;
               }
           }
           break;
       case
"w"
:
          
// Only simple seconds calculation needed from here on
          
$diff = floor($seconds / 604800
);
           break;
       case
"d"
:
          
$diff = floor($seconds / 86400
);
           break;
       case
"h"
:
          
$diff = floor($seconds / 3600
);
           break;       
       case
"i"
:
          
$diff = floor($seconds / 60
);
           break;       
       case
"s"
:
          
$diff = $seconds
;
           break;       
   }

   return
$diff
;
}
?>
vitorsuporte at hotmail dot com
03-Oct-2005 08:48
If you want to use date(?W?, <TIME_STAMP>) to generate week numbers for mysql querys, you need to set the "mode" argument in the mysql YEARWEEK() function to a value that returns only weeks that have more than 3 days (1, 3, 4, 6).
Example:
<?php
$sql
= ?SELECT project_name FROM project WHERE YEARWEEK(project_start_date, 1) = ?.date(?W?
);
?>

Check MySQL manual for more details.
john at ellingsworth dot org
03-Oct-2005 11:40
In response to the recommendation from Liam regarding adding days to a date (which is quite handy):

To maintain the format suggested at the top of your code, the $pay_date needs to be formatted using date() & mktime():

$pay_date = date("d - m - Y",mktime(0,0,0,$month,$final,$year));

and:

$pay_date = date("d - m - Y",mktime(0,0,0,$month,$next_term,$year));

This keeps the leading zero in your days and months.
liam at sunwise dot co dot uk
24-Sep-2005 05:43
If you wish to add a certain amount of days on from the present date then this should work. Just change the $invoice_day to the amount of days you wish to add on! This also takes into account the months and years, as you wouldn't want 42-10-05 as the next date! This will work well for adding upto 28 days from the present.

<?php

$month
= date("m"
);
$year = date("Y"
);
$day = date("d"
);

$last_day = date( "d", mktime(0, 0, 0, $month + 1, 0, $year
) ) ;

$invoice_day = 14
;

echo
'The invoice will be due in '.$invoice_day.' days.<br><br>'
;

$next_term = $day + $invoice_day
;

if (
$last_day < $next_term
){
echo
"The last day of the month is $last_day"
;
$final = $next_term - $last_day
;
echo
'.<br><br>'
;

$month = $month + 1
;

if (
$month == '13'
){
$year = $year + 1
;
$month = '01'
;
}

$pay_date = $final.' - '.$month.' - '.$year
;
echo
"This will make the invoice due date the $pay_date"
;

}else{

echo
"The last day is $last_day. <br>"
;
$pay_date = $next_term.' - '.$month.' - '.$year
;
echo
"This will make the invoice due date the $pay_date"
;

}

?>

Hope it helps anyone,
Liam
:-)
igor dot felluga at gmail dot com
22-Sep-2005 11:53
I write a small function that return the number of time that you find a weekday (Monday,Tuesday,...) in an year;

function countWeekDay($WD,$year) {
   $d=$WD-date("w",mktime(0,0,0,1,1,$year));
   $n=0;
   for($i==0;$i<54;$i++){
       $time=mktime(0,0,0,1,1+$d+($i*7),$year);
       if(date("Y",$time)==$year) $n++;
   }
   return $n;
}

$WD is the weekday Monday = 1;
daykay at pdsoftware dot de
21-Sep-2005 07:02
If you need to handle the number of the current weekday keep attention of this:

echo date("w", mktime(0, 0, 0, 9, 21, 2005));

output = 3
(american day count sunday = 0)

but:

echo date("w", mktime(0, 0, 0, 09, 21, 2005));

output = 2
(monday = 0)

I was wondering! Do we europeans always type our date like 09.08.05 ? :)
Thava --- thava16 at hotmail dot com
20-Sep-2005 02:41
This will return the N possible future dates acording to your selections of parameters
mydates_array([Which Week in a Month],[Which Day in a Week],[No of Dates have to return])
Eg:- Every 2nd Sunday mydates_array(2,0,10)
$Dateid---> Sunday            - 0 ,    Monday        - 1 ,    Tuesday        - 2,    Wednesday    - 3,
  
             Thursday                - 4 ,    Friday        - 5 ,    Saturday    - 6
$weekid---> * can not be greater than 6
           * if weekID is equal 6 it will return the Last Day of the weeek.
           * Eg:-mydates_array(6,1,10);
           * it will Returns 10 Last Mondays
           * Please note weekid 5 is not availble in all months.mydates_array will not returns $no_returns that you want.
           * Eg:-mydates_array(5,1,10);
           * it will Returns 5th Monday
$no_returns--> No of dates that you want
By: Rajaratnam Thavakumar(thava16@hotmail.com)           
<?php
function mydates_array($weekid,$Dateid,$no_returns
){
  if(
$weekid<=6
){
  
$todayweek = date("D"
);
  
$myarr=array("Sun","Mon","Tue","Wed","Thu","Fri","Sat"
);
   for(
$k=0;$k<=6;$k
++){
       if (
$todayweek==$myarr[$k
]){
           if(
$k==0
){   
              
$currentdate=0
;
           }else{
              
$currentdate=$k
;
           }
     }
   }
    
//get Dateid ----------------
  
if($Dateid==0
){
      
$Newmyday=date("d")-$currentdate
;
   }else if (
$Dateid==1
){
      
$Newmyday=date("d")-($currentdate-1
);
   }else if (
$Dateid==2
){
      
$Newmyday=date("d")-($currentdate-2
);
   }else if (
$Dateid==3
){
      
$Newmyday=date("d")-($currentdate-3
);
   }else if (
$Dateid==4
){
      
$Newmyday=date("d")-($currentdate-4
);
   }else if (
$Dateid==5
){
      
$Newmyday=date("d")-($currentdate-5
);
   }else if (
$Dateid==6
){
      
$Newmyday=date("d")-($currentdate-6
);
   }
  
$thisweekId=$weekid
;
  
$count=0
;
  
$column=0
;
  
$myval=$no_returns*5
;
   for(
$i=1; $i<=$myval; $i
++){
      
$week1a = mktime(0, 0, 0date("m"), $Newmydaydate("Y"
));
      
$week123=strftime("%Y-%m-%d", $week1a
);
      
$Newmyday=$Newmyday+7
;
       list (
$iyear, $imonth, $idate) = split ('[-.-]', $week123
); 
          
//Insert Dates into Array
            
if( $idate<10
){
            
$idate=trim(str_replace('0','',$idate
));
             }
          
$myweekno=ceil(($idate + date("w",mktime(0,0,0,$imonth,0,$iyear)))/7
);
            
$row=$myweekno-1
;
                  
$Mymonth[$i]=$imonth
;
                   if (
$i>1
){
                   if (
$Mymonth[$i-1]!=$Mymonth[$i
]){
                    
$column=$column+1
;
                   }
                   }
                  
$EveDates[$row][$column]=$week123
;
     }
  
$count=0
;
   for (
$column = 0; $column < $no_returns; $column++ ){ 
//--for1-----
  
$mynewcount=0

       for(
$row = 0; $row < 6; $row++){
//--for2-----
          
if($EveDates[$row][$column]!="" && $thisweekId!=6
){
               list (
$iyear1, $imonth1, $idate1) = split ('[-.-]', $EveDates[$row][$column
]);
              
$myweekno=ceil(($idate1 + date("w",mktime(0,0,0,$imonth1,0,$iyear1)))/7
);
                
$mynewcount=$mynewcount+1
;
                   if(
$mynewcount==$thisweekId
){
                          
$week_n1= mktime(0, 0, 0, date("m"), date("d"),  date("Y"
));
                          
$week_m1=strftime("%Y-%m-%d", $week_n1
);
                           if(
$count < $no_returns && $EveDates[$row][$column] >= $week_m1
){
                              
$mydates_array[$count]=$EveDates[$row][$column
];
                           }
                      
$count=$count+1
;
               }
           }
           else{
            
$mycount=0
;
             if (
$row==5 && $thisweekId==6
){
                 for(
$e=5; $e>=0; $e
--){
                   if(
$EveDates[$e][$column]!=""
){
                   break;
                   }
                 }
                  
$week_n1= mktime(0, 0, 0, date("m"), date("d"),  date("Y"
));
                  
$week_m1=strftime("%Y-%m-%d", $week_n1
);
                   if(
$mycount<$no_returns && $EveDates[$e][$column] >= $week_m1
){
                      
$mydates_array[$count]=$EveDates[$e][$column
];
                   }
                  
$mycount=$mycount+1
;
                  
$count=$count+1

             }
           }
       } 
//--End of for2-----
  
}
//--End of for1-----
 
return $mydates_array
;
}else{
echo(
'WeekID Cant be  more than six!'
);
}}
?>
<select name="eventDate" style="border:1 solid #000066" >
<?   
// Return 10 Every 2nd Monday dates
$myarray=mydates_array(2,1,10
);
 for (
$i=0;$i<count($myarray);$i
++){
   list (
$iyear, $imonth, $idate) = split ('[-.-]', $myarray[$i
]);
  
$week1a = mktime(0, 0, 0,$imonth, $idate$iyear
);
  
$week= strftime("%A %d %B %Y", $week1a
);
?>
<option  value="<?=$myarray[$i]?>"><?=$week?></option>
<? }
?>
</select>
klaux1 at yahoo dot com dot br
19-Sep-2005 01:44
<?php

/**
 * Translate date format
 *
 * Translate date number format
 * @package trDate
 * @author Clauzio C. Perp鴵o
 * @version 0.1
 * @copyright licence above
 */
class trDate
{

 
/**
   * get trDate
   * @access static public
   * @param string $in
   * @param string $out
   * @param string $date
   */
 
static public function get ($in, $out, $date
)
  {

  
$reg = '^([-/\ Yymndj]{8,10})$'
;
   if (!
ereg($reg, $in.$out
))
     return
1
;

  
$date = ereg_replace('[/\ ]', '-', $date
);
  
$_date = explode('-', $date
);
  
$date = sprintf('%02u', $_date[0
])
     .
sprintf('%02u', $_date[1
])
     .
sprintf('%02u', $_date[2
]);

  
$in = ereg_replace('[/\ -]', '', $in
);

   for (
$i=0; $i<strlen($in); $i
++) {
    
$v = $in[$i
];

     if (
ereg('[Y]', $v
))
      
$len = 4
;
     elseif (
ereg('[ymndj]', $v
))
      
$len = 2
;

    
$dt[$v] = substr($date, 0, $len
);
    
$date = substr($date, $len
);
   }

  
$dt['Y'] = $dt['y'] <= date('y') ? '20'.$dt['y'] : '19'.$dt['y'
];
  
$dt['y'] = substr($dt['Y'], 2
);

  
$dt['m'] = $dt['n'
];
  
$dt['n'] = (int) $dt['m'
];

  
$dt['d'] = $dt['j'
];
  
$dt['j'] = (int) $dt['d'
];

  
$j = 0; $o_dt = $sp
= array();
   for (
$i=0; $i<strlen($out); $i
++) {
    
$v = $out[$i
];

     if (!
ereg('[Yymndj]', $v
))
      
$sp[$j++] = $v
;
     else
      
$o_dt[] = $dt[$v
];
   }

  
$ret = $o_dt[0
]
     . @
$sp[0
]
     .
$o_dt[1
]
     . @
$sp[1
]
     .
$o_dt[2
];

   return
$ret
;
  }
}

//TEST
$date = '4/75-23'
;
echo
trDate::get('n/y-j', 'Ymd', $date)."\n";
//19750423
//END TEST

?>
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
++;
       }
?>
cml at dokuro dot org
12-Sep-2005 08:11
Here is a functiom that returns table:
$table[week_number] = week_starting_day

<?

function get_weeks($year
) {
          
$firstday_ts = mktime(1,0,0,1,1,$year
);
          
$firstday = date("w", $firstday_ts
);

           switch(
$firstday
) {
              
              
// first day of this year is monday
              
case 1
:
                  
$first = $firstday_ts
;
                  
$i=0
;
                   break;
              
              
// any other day - first day in this week will be in prev. year
              
default:
                  
// sunday - 7th day of week
                  
if(!$firstday) $firstday = 7
;
                  
                  
// else
                  
$first = strtotime("-".($firstday - 1)." day", $firstday_ts
);
                  
$weeks[0] = date("Y-m-d", $first
);
                  
$i=1
;
                  
$first = strtotime("+7 day",$first
);
                   break;
           }

           for(;
$year == date("Y", $first); $i++, $first = strtotime("+7 day",$first
))
              
$weeks[$i] = date("Y-m-d", $first
);

           return
$weeks
;
}

?>
Michiel vd Vis
07-Sep-2005 11:20
I created a function which calculates the days since the epoch:

// @param date: Date formatted like "DD-MM-YYYY"
// @return Days since epoch
function daysSinceEpoch($date)
{
     $date = explode("-", $date);
     $years = $date[2] - 1970;

     $tot_days = $years * 365;
     $tot_days += floor(($years + 1) / 4); // Add
     $tot_days += date("z", mktime(1,0,0,round($date[1]),round($date[0]),$date[2]));
     return $tot_days;
}

TODO: Error catching
TODO: Support for dates < 1-1-1970 AND > 2031
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!
Greg
02-Sep-2005 01:45
I had a situation where I wanted to generate the name of all months from their numerical representation in a for/loop.

To do this:

$foo being numerical representation of month (1-12)

for ($foo=1; $foo<=12; $foo++)
{
     echo date("F", mktime(0, 0, 0, $foo)) ;
}

Will return name of month dependant on $foo value.

If $foo == 1, January is returned etc.

Very useful when creating select/option HTML boxes.
trucex at gmail
28-Aug-2005 10:24
In response to aedude (gordon from freepgs.net):

I have modified your function so it makes more sense and is more useful.

<?php

function datediff($date1, $date2
) {
// $date1 is subtracted from $date2.
// if $date2 is not specified, then current date is assumed.

//Splits date apart
list($date1_month, $date1_day, $date1_year) = split('[/.-]', $date1
);

if (!
$date2
) {
 
$date2_year = date("Y");
//Gets Current Year
 
$date2_month = date("m");
//Gets Current Month
 
$date2_day = date("d");
//Gets Current Day
} else {
  list(
$date2_month, $date2_day, $date2_year) = split('[/.-]', $date2
);
}

$date1 = mktime(0,0,0,$date1_month, $date1_day, $date1_year);
//Gets Unix timestamp for $date1
$date2 = mktime(0,0,0,$date2_month, $date2_day, $date2_year);
//Gets Unix timestamp for $date2

$difference = $date2-$date1;
//Calcuates Difference
return floor($difference/60/60/24);
//Calculates Days Old
}
?>

New Usage:

<?
//Get how many days since a file has been modified:
echo "$file was modified " . datediff($filemtime($file), 0) . " days ago."
;

//Outputs:
// Somefile.txt was modified 6 days ago.
?>

Or

<?

$sally_bday
= "11-10-87"
;
$frank_bday = "11-05-86"
;
echo
"Frank is " . datediff($frank_bday, $sally_bday) . "days older than Sally."
;

//Outputs:
//Frank is 370 days older than Sally.
?>

As you can see, either example can be expanded upon greatly. Keep in mind this function does not do well with leap years or more precise time as-is, though it could be modified to do so if needed. A more practical use for this is to do something like delete files older than 30 days from a server, or see which file/value is older.
Thiago Moretto thiago{at}moretto.eng.br
19-Aug-2005 07:36
<?php
// for bitwise operations... =]
define(D_YEAR, 1
);
define(D_MONTH, 2
);
define(D_WEEK, 4
);
define(D_DAY, 8
);
define(D_HOUR, 16
);
define(D_MINUTE, 32
);
define(D_SECOND, 64
);
function
difftimetostring($difftime, $Opt = 0
)
{
   if (
$Opt == 0) $Opt = D_YEAR | D_MONTH | D_DAY | D_HOUR | D_MINUTE
;
  
$diffstring = null
;
  
$BissextFix = floor ($difftime / ((3600 * 24) * 366
));
   for(
$i=(date('Y') - $BissextFix); $i < date('Y'); $i
++)   
       {
          
$x = 0 + ($i / 4
);
           if ((
$x - floor($x)) == 0
)
            
$bissextyears
++;
       }
  
   if (
$Opt & D_YEAR
) {
      
$years = floor($difftime / (3600 * 24 * (365 + $bissextdays
)));
      
$difftime = $difftime % (3600 * 24 * (365 + $bissextdays
));
   }
  
   if (
$Opt & D_MONTH
) {
      
$months = floor($difftime / (3600 * 24 * ((365  + $bissextdays)/12
)));
      
$difftime = $difftime % (3600 * 24 * ((365  + $bissextdays)/12
));
   }
  
   if (
$Opt & D_WEEK
) {
      
$weeks = floor($difftime / (3600 * 24 * 7
));
      
$difftime = $difftime % (3600 * 24 * 7
);
   }
  
   if (
$Opt & D_DAY
) {
      
$days = floor($difftime / (3600 * 24
));
      
$difftime = $difftime % (3600 * 24
);
   }
  
   if (
$Opt & D_HOUR
) {
      
$hours = floor($difftime / 3600
);
      
$difftime = $difftime % 3600
;
   }
  
   if (
$Opt & D_MINUTE
) {
      
$minutes = floor($difftime / 60
);
      
$difftime = $difftime % 60
;
   }
  
   if (
$Opt & D_SECOND
) {
      
$seconds = $difftime
;
   }
        
  
$diff
= array();
  
// Ano
  
if($years > 0 && $years > 1
)
      
array_push($diff, $years . ' anos'
);
   else if (
$years == 1
)
      
array_push($diff, ' 1 ano'
);
      
  
// Meses
  
if($months > 0 && $months > 1
)
      
array_push($diff, $months . ' meses'
);
   else if (
$months == 1
)
      
array_push($diff, $months . ' m곧
);

  
// Semanas
  
if($weeks > 0 && $weeks > 1
)
      
array_push($diff, $weeks . ' semanas'
);
   else if (
$weeks == 1
)
      
array_push($diff, '1 semana'
);
          
  
// Dias
  
if($days > 0 && $days > 1
)
      
array_push($diff, $days . ' dias'
);
   else if (
$days == 1
)
      
array_push($diff, '1 dias'
);

  
// Horas
  
if($hours > 0 && $hours > 1
)
      
array_push($diff, $hours . ' horas'
);
   else if (
$hours == 1
)
      
array_push($diff, '1 hora'
);
      
  
// Minutos
  
if($minutes > 0 && $minutes > 1
)
      
array_push($diff, $minutes . ' minutos'
);
   else if (
$minutes == 1
)
      
array_push($diff, '1 minutos'
);
  
  
// Segundos
  
if($seconds > 0 && $seconds > 1
)
      
array_push($diff, $seconds . ' segundos'
);
   else if (
$seconds == 1
)
      
array_push($diff, '1 segundo'
);
      
   return
implode(', ', $diff) . ' atr᳧
;
}

$DiffDate = time() - mktime(13, 30, 23, 3, 22, 1998
);
$DiffDateString = difftimetostring($DiffDate, 0
);
echo
$DiffDateString
;
?>
javascripts at planet dot nl
17-Aug-2005 11:46
Here is an almost complete implementation in JavaScript
Feel free to streamline, improve and bugfix, not to mention to fix the missing ones :)

http://home.planet.nl/~javascripts/phpDate.html

Michel
steve at somejunkwelike dot com
16-Aug-2005 06:01
re: Paul_liversidge...

This is a way to get the next 10 business days, by comparing the day of the week to not be saturday or sunday.  change the top two variables to get various different results...  if you want to get the next 10 business days, starting in two days from today, change the first variable to 2, and the second to 14.  This should yield the next 10 working days.

<?php

$how_many_business_days_ahead
= 0
;
$how_many_business_days_to_count = 7
;

for (
$i=0;$i<$how_many_business_days_to_count;$i
++)
   {
  
$jump=$i+$how_many_business_days_ahead
;
  
$evalday = mktime(strftime ("%d/%m/%Y", strtotime("+$jump days"
)));
  
$theday = strftime("%A", strtotime("+$jump days"
));   
   if(
$theday != "Saturday" and $theday != "Sunday"
)
       {
      
$days = $how_many_business_days_ahead+$i
;
      
$the_days[$j] = strftime("%A, %B %d, %Y", strtotime("+$jump days"
));
      
$j
++;
       }
   }
  
  
$k = $how_many_business_days_ahead
;
  
   foreach(
$the_days as $eachday
)
       {
       echo
"$k business days from now = $eachday<br />"
;
      
$k
++;
       }
  
  
?>

results:

0 business days from now = Tuesday, August 16, 2005
1 business days from now = Wednesday, August 17, 2005
2 business days from now = Thursday, August 18, 2005
3 business days from now = Friday, August 19, 2005
4 business days from now = Monday, August 22, 2005
ae-dude at mchsi dot com
11-Aug-2005 03:58
To calculate how many days old something is is very simple.

<?php

function age($BirthDate, $do
)
{

if (
$do == "") { $do = "1"; }
//Checks if do is set, default set is number of days

list($month1, $day1, $year1) = split('[-.]', $BirthDate);
//Splits date apart

$year = date("Y");
//Gets Current Year
$month = date("m");
//Gets Current Month
$day = date("d");
//Gets Current Day

$date = mktime(0,0,0,$month,$day,$year);
//Gets Unix timestamp for current date
$date1 = mktime(0,0,0,$month1,$day1,$year1);
//Gets Unix timestamp for date set

$difference = $date-$date1;
//Calcuates Difference
$days2 = floor($difference /60/60/24);
//Calculates Days Old

//If you choice "2" which is status unstead of days you can modify it here!
if ($days2 <= "20") { $days1 = "2 Weeks"
; }
if (
$days2 <= "13") { $days1 = "1 Week"
; }
if (
$days2 <= "7") { $days1 = "New"
; }
if (
$days2 >= "21") { $days1 = "Old"
; }
//End Status Modify

if ($do == "1") { echo $days1; }
//Echo Status
if ($do == "2") { echo $days2; }
//Echo Days
}
?>

Then just put this where ever you want the days or status to show
age('MM-DD-YYYY', 'S')

Replace MM with the month it was made or born
DD with the day
YYYY with the year

S is what format you want it to show, if you want the days of something such as how many days a post has been posted enter "2".
If you want status like "New, 1 week, 2 weeks, Old" then enter "1".

Hope you enjoy.

Gordon
FreePgs.com Tech
angstsix at gmail dot com
09-Aug-2005 01:30
same code as djneoform at gmail dot com,
but added the split function to make things a little simpler for getting age from birthdate

<?
function persons_age($BirthDate
)
{

list(
$year, $month, $day) = split('[-.]', $BirthDate
);

  
$tmonth = date('n'
);
  
$tday = date('j'
);
  
$tyear = date('Y'
);
  
$years = $tyear - $year
;
   if (
$tmonth <= $month
)
   {
       if (
$month == $tmonth
)
       {
           if (
$day > $tday
)
              
$years
--;
       }
       else
          
$years
--;
   }
   echo
$years
;
}

persons_age('1978-12-06'
)
?>
james dot baxter at november54 dot com
07-Aug-2005 08:04
Heres something i've written to (a) figure the age from DOB in the sql format YYYY-MM-DD (b) Check the member is over 18 which I need to do before allowing the content to be viewed.

$User_DoB contains the Date of Birth taken from the members database.

<?php

$DoB_Array
= explode("-", $User_DoB
);
$Today_Array = explode("-", date('Y-m-d'
));

// _Array[0] is the year, _Array[1] is the month, _Array[2] is the day.
  
if ($Today_Array[1] > $DoB_Array[1] || ($Today_Array[2] >= $DoB_Array[2] && $DoB_Array[2] == $Today_Array[2
])) {
  
$Age = $Today_Array[0] - $DoB_Array[0
];
} else {
  
$Age = $Today_Array[0] - $DoB_Array[0] - 1
;
}

if (
$Age < 18
) {
  
$Error[11] = 1
;
}

?>

If the rest of the code found $Error[11] to have the value of 1 the user would be informed they're not allowed to view the content and redirected to a "safe" page.

I think this is the best possible way I could have done it, if theres a better way please let me know.
djneoform at gmail dot com
06-Aug-2005 03:18
here's a function to get (in years) a person's age based on their birthday

function persons_age($year, $month, $day)
{
   $tmonth = date('n');
   $tday = date('j');
   $tyear = date('Y');
   $years = $tyear - $year;
   if ($tmonth <= $month)
   {
       if ($month == $tmonth)
       {
           if ($day > $tday)
               $years--;
       }
       else
           $years--;
   }
   return $years;
}
Rob Muhlestein
05-Aug-2005 05:48
All functions that have anything to do with the internal 32-bit constrained time() system call will have this same limitation. Hopefully we'll be 64 bit by long before then, although this already creating problems with UNIX internals.
thammer at rtccom dot com
04-Aug-2005 04:46
Relative dates (ie, Today, Yesterday, etc..) are missing from the date function. So I wrote this function to replace date(). It returns  Today, Yesterday, or Day of the Week relative to {today} up to 6 days. Anything older than that, and it will use the formatting you would normally apply to date(). I hope somebody finds this useful.

<?
//Returns Today,Yesterday, Day of week ('l')
//up to 6 days ago. Otherwise it uses $format
function RelativeDate($format,$epoch
) {
  
$day    = date('j',$epoch
);
  
$today  = date('j',time
());
  
$yday  = date('j',strtotime("-1 day"
));

  
//account for last month's day
  
switch($day
) {
       case
$today:    return "Today"
;                break;
       case
$yday:    return "Yesterday"
;            break;
       default:       
          
//Look up to one week ago
          
for($i=1;$i<=6;$i
++) {
              
$pastday = date('j',strtotime("-$i days"
));
               if(
$day == $pastday
) {
                   return(
date('l',$epoch
));
               }
           }
          
          
//If we made it to here, just print the format given
          
return date($format,$epoch
);
   }
}

?>
ove at junne dot dk
03-Aug-2005 06:39
I seems to me that we're rapidly apporaching another Y2K event. The date-function only handles dates up to 2038, and this is only some 30 years away. Even today is it impossible to use date() to represent my children's 50 years birthday.

Just think about it, when you're designing your code.
daemon [AT] fragmentized [DOT] com
26-Jul-2005 05:46
Actually, here is an easier way to get yesterday's date:

<?php
$yesterday
= strftime ("%d/%m/%Y", strtotime("-1 day"
));
echo
$yesterday
;
?>
vemod at gmx dot net
12-Jul-2005 08:52
improved in sence of code style version of validation posted by development at lab-9 dot com in may 2005

   function schaltjahr($jahr){
       return (bool)($jahr % 400 == 0) || ($jahr % 4 == 0 && $jahr % 100 != 0);
   }

   function isDate($agv){
       if(!ereg('^([0-9]{1,2})-([0-9]{1,2})-([0-9]{4})$',
           $agv,$agv))
           return false;
       if(is_numeric($agv[3])){
           if($agv[3] >= 1950){
               if(is_numeric($agv[2]) && $agv[2] >= 1
                   && $agv[2] <= 12){
                   if(is_numeric($agv[1]) && $agv[1] >= 1){
                       if($agv[2] == 2)
                           return (($schaltjahr_days=(schaltjahr($agv[3]))?29:28) && $agv[1]<=$schaltjahr_days);
                       else{
                           if($agv[2] >= 8) $agv[2]++;
                           if($agv[2] % 2 == 1
                             && ($agv[1] <= 31 && $agv[1] >= 1))
                                   return true;
                           if($agv[2] % 2 == 0
                               && ($agv[1] <= 30 && $agv[1] >= 1))
                                   return true;
                       }
                   }
               }
           }
       }
       return false;
   }
stuff at rushsoft dot de
30-Jun-2005 09:13
ISO 8601:2000 defines:
[...] day of the year is represented by three decimal digits. The first day of any year is represented by [001] and
subsequent days are numbered in ascending sequence [...]

So don't forget increasing the return value of date("z") by one to be ISO conform, if you use this, for instance, on presentation level.
ungu at terong dot com
23-Jun-2005 05:26
For those of you non PHP 5 users but wants to have a similar functionality as 'c' option (ISO 8601 date), you can use my short snippets below:

<?
function get_iso_8601_date($int_date
) {
  
//$int_date: current date in UNIX timestamp
  
$date_mod = date('Y-m-d\TH:i:s', $int_date
);
  
$pre_timezone = date('O', $int_date
);
  
$time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2
);
  
$date_mod .= $time_zone
;
   return
$date_mod
;
}

echo
get_iso_8601_date(time
());
?>
witcho at gmail dot com
07-Jun-2005 04:22
When using 'z' it should be used as how many days have passed since the beginning of the year; not as the day of the year.
"January 1" is the day 1 of the year not the day 0.
Better to add 1 when using 'z' if you really want to know the day of the year.
justin at drunkatgt dot com
04-Jun-2005 03:24
In response to pmcdevitt(at)cesales.com:

If you just want to find out what last month was, try
$lastmonth=mktime(0,0,0,date("m")-1,1,date("Y"));
$lastmonth= date("M", $lastmonth);

There is no reason to use the day of the month to determine the revious month.  And every month has a 1st.  You could even through an arbitrary year in there to save a fraction of a calculation.
searcher cookie dracon dot biz
22-May-2005 11:49
There is always a confusion with daylight saving time and how your server handles it, so here's a simple and quick fix

<?
# ~~~ GMT Time Magic v2.1 ~~~~~~~~~~ #
function GMT_Time($Stamp,$Change
) {
   return ((
$Stamp == 0) ? time() : $Stamp) - $Change * date("Z"
);
}
?>

And the final calling code for both gmdate() and gmmktime() commands

<?= date("l, F jS Y, H:i:s", GMT_Time($Timestamp,1) + 3600 * $Timezone) ?> 
- and -
<?= GMT_Time($Timestamp,(-1)) + 3600 * $Timezone ?> 

The tool based on this code can be found and freely used here:
http://www.dracon.biz/timestamp.php
Vladimir Kornea of typetango.com
04-May-2005 03:34
<?php
$mysql_datetime
= date('Y-m-d H:i:s'
);
$mysql_date = date('Y-m-d'
);
$mysql_time = date('H:i:s'
);
?>

I'm probably not the only one who keeps forgetting it.
ggravarr
03-May-2005 07:57
simple Function to return the nth day of the week of the month for a given timestamp

function DoWoM($ts) {
   return ((integer)(date("d",$ts)/7)+(((date("d",$ts)%7)>=date("w",$ts)) ? 1 : 0));
}
MG_Peter at o2 dot pl
30-Apr-2005 12:05
easy way - to convert a "datetime" form mySQL into php date format....
first - get the array form mySQL, then use

<?php
date
("d M Y H:i:s", strtotime($your_row['lastlogin_date'
]))
?>

strtotime - easy converts a datetime timestamp into time  ( time() or date("U")).
llewellyntd at gmail dot com
29-Apr-2005 12:50
Here is a very easy way to get the difference, in days, between two dates:

$days = (strtotime("2005-12-31") - strtotime(date("Y-m-d"))) / (60 * 60 * 24);
print $days;
paul_liversidge at hotmail dot com
27-Apr-2005 08:03
A quick function to calculate the number of working days between two dates in YYYY-MM-DD format *without* iterating through every day and comparing it to the weekday. The start and end dates are included in the calculation. I don't know how to easily explain the final calculation, I just happened to notice the pattern in the test data and this is how I ended up expressing it. :)

<?php
function CalcWorkingDays ($start, $end
) {
 
$starttime = gmmktime (0, 0, 0, substr ($start, 5, 2), substr ($start, 8, 2), substr ($start, 0, 4
));
 
$endtime = gmmktime (0, 0, 0, substr ($end, 5, 2), substr ($end, 8, 2), substr ($end, 0, 4
));
 
$days = (($endtime - $starttime) / 86400) + 1
;
 
$d = $days % 7
;
 
$w = date("w", $starttime
);
 
$result = floor ($days / 7) * 5
;
 
$result = $result + $d - (($d + $w) >= 7) - (($d + $w) >= 8) - ($w == 0
);
  return
$result
;
}
?>
php at webparlour dot com
20-Apr-2005 12:12
This may be ULTRA SIMPLISTIC, but having this example would have saved me (a PHP newbie) some time trying to figure out how to adjust the local server time to a different local time.

Essentially, I started out with:

$appdate = date("F jS Y, h:iA.");

Which captures the *local server time* in $appdate:

April 20th 2005, 04:44AM.

BUT...

The *local time* I needed reflected in the variable is 3 hours later. To accomplish this very simply, add the "time()" modifier like so:

$appdate = date("F jS Y, h:iA.", time() + 10800);

Which captures the *ADJUSTED local server time* in $appdate:

April 20th 2005, 07:44AM.

So, adding " time() + 10800" to the normal Date() function ADDS 3 hours (10800 seconds!) to the local server time.

Hope this helps others struggling to make this very basic adjustment.

Cheers,

Jem
kostya_r at hotmail dot com
11-Apr-2005 01:41
I have created a simple script which calculates current week number of current month.

<?php

// Calculates current week number of the month

$week=(integer)date('W')-(integer)date('W', mktime(0, 0, 0, date('n'), 1, date('Y'
)));

?>
bhaveshsurani at gmail dot com
09-Apr-2005 04:40
There is functionality to calculate the difference between two dates
and get an array.  I did this function to calculate any weekday between two dates. Dateformat should be in 'DD-MM-YYYY' and Numeric representation of the day of the week is 0 (for Sunday) through 6 (for Saturday). .

function getDayCount($fromDate, $toDate, $weekDay){
   $fst = explode("-", $fromDate);
   $first = date("Y-m-d", strtotime($fst[2] . "-" . $fst[1] . "-" . $fst[0]));
   $end = explode("-", $toDate);
   $last = date("Y-m-d", strtotime($end[2] . "-" . $end[1] . "-" . $end[0]));
  
   //Initialize a today and day counter variables
   $today = $first;
   $dayCount = 0;
   while ($today<=$last){
       $today = date("Y-m-d", strtotime("+1 days", strtotime($today)));
       $day = date("w", strtotime("+1 days", strtotime($today)));
       if($day == $weekDay)
           $dayCount++;
   }
   return $dayCount;
}
hossy at hossy dot com
08-Apr-2005 05:49
This note is in reply to bhaveshsurani at gmail dot com:

There is functionality to calculate the difference between two dates and get an array.  I did this function to calculate my age:

function getmyage() {
   $bday = gmmktime(14,29,0,9,23,1981)+(60*60*5);
   //The '+mktime(0,0,0,1,1,1970)' will add the local server's GMT offset to the time.
   //This will convert the server's current local time to GMT.
   //This is needed because $bday is calculated for a specific time zone (Central w/ DST:  GMT-05:00)
   $dif = (time() + mktime(0,0,0,1,1,1970)) - $bday;
   $dif = getdate($dif);
   //Since mktime calculates the time from the Unix Epoch (January 1 1970 00:00:00 GMT), subtract 1970 from the year value.
   return ($dif['year'] - 1970);
}

Hope this helps.
bati1927 at msn dot com
06-Apr-2005 04:48
This function convert date format.

<?php
function dateFormat($input_date, $input_format, $output_format
) {
  
preg_match("/^([\w]*)/i", $input_date, $regs
);
  
$sep = substr($input_date, strlen($regs[0]), 1
);
  
$label = explode($sep, $input_format
);
  
$value = explode($sep, $input_date
);
  
$array_date = array_combine($label, $value
);
   if (
in_array('Y', $label
)) {
      
$year = $array_date['Y'
];
   } elseif (
in_array('y', $label
)) {
      
$year = $year = $array_date['y'
];
   } else {
       return
false
;
   }
  
  
$output_date = date($output_format, mktime(0,0,0,$array_date['m'], $array_date['d'], $year
));
   return
$output_date
;
}

$mydate = "16/04/02"
;
echo (
'date input: '.$mydate.' -> date output: '.dateFormat($mydate, 'd/m/y', 'Y-m-d'
));
?>

This code will output: 16/04/2002 -> 2002-04-16

if you don't use PHP5 you can implement array_combine function by:

<?php
if (!function_exists('array_combine'
)) {
   function
array_combine($a1, $a2
) {
       if(
count($a1) != count($a2
))
           return
false
;
           if(
count($a1) <= 0
)
           return
false
;
      
$a1 = array_values($a1
);
      
$a2 = array_values($a2
);
      
$output
= array();
       for(
$i = 0; $i < count($a1); $i
++) {
          
$output[$a1[$i]] = $a2[$i
];
       }
       return
$output
;
   }
}
?>
oscar at montur dot net
04-Apr-2005 03:02
About the GetDateArray function below. I think there are much easier ways to do it, using strtotime and date.

function GetDateArray($first, $last)
{
   //Convert dates to php format
   $fst=explode("/", $first);
   $first=date("Y-m-d", strtotime($fst[2] . "-" . $fst[1] . "-" . $fst[0]));
   $end=explode("/", $last);
   $last=date("Y-m-d", strtotime($end[2] . "-" . $end[1] . "-" . $end[0]));
   //Initialize a today variable
   $today=$first;
   while ($today<=$last)
   {
       $DateArr[]=$today;
       $today=date("Y-m-d", strtotime("+1 days", strtotime($today)));
   }
   return $DateArr;
}
djmaze(AT)cpgnuke(.)com
27-Mar-2005 07:53
PHP date, strftime and mktime functions are DST sensitive
This means if the server is setup to be US GMT-5 and DST sensitive then the mentioned functions add, extract or do nothing with the current DST.

Without a given timestamp:
   - date() uses the current server time.
     This is DST affected if the server uses DST settings
   - gmdate() uses the current GMT time, it extracts server GMT & DST.

With a given timestamp:
   - date() is affected if the server uses DST settings
     * if current time is DST but the given time isn't then DST is extracted
     * if current time isn't DST but the given time is then DST is added
   - gmdate() is affected, it extracts server GMT & DST on the given timestamp

So for example $timestamp is a GMT based time.
You modify the $timestamp for a "member" his personal timezone and dst.
The member has setup GMT-5 and DST sensitive
You add his GMT-5 to the $timestamp and check if the $timestamp is in DST or not

Then all the above functions  are screwed in normal use.

<?php

$timestamp
= 1122814800;
// 07/31/05 13:00:00 GMT
$user_gmt = -5
;
$user_dst = 1
;

$timestamp += ($user_gmt*3600);
// to user time
$timestamp += 3600;
// user time is in DST

echo date("H:i:s",$timestamp
);
echo
gmdate("H:i:s",$timestamp
);

?>

If server is GMT+0 in summer (DST is on) the above outputs

08:00:00
07:00:00

If server is GMT+0 in winter (DST is off) the above outputs
09:00:00
08:00:00

If server is GMT-5 in winter (DST is off) the above outputs
09:00:00
03:00:00

So if you work with local times and the server isn't GMT based be carefull how you output the times to your members.
rcrodgers622 at gmail dot com
25-Mar-2005 06:08
Regarding dolso at elastech dot it's note, it's actually easier to use the 't' item to get the last day of any given month.

echo 'February ' . date('t',mktime(0,0,0,2,1,2004)) . ' is the last day of February 2004';
//Displays "The February 29 is the last day of February 2004"

The actual day of the month specified in mktime() is irrelevant, but it's best and safest to use a day that won't alter the results such as the first of the month.
dolso at elastech dot it
24-Mar-2005 06:52
To get the last day of a given $month/$year:

<?php

   $last_day_of_month
= date( "d", mktime(0, 0, 0, $month + 1, 0, $year
) ) ;

?>

Tommy
david dot niry at wanadoo dot fr
24-Mar-2005 10:19
After using this function, it appears there is a small error with the post from squid at anime-sanctuary dot net. The logic is actually reversed.

if($cur_month>$dob_month || ($dob_month==$cur_month && $cur_day>=$dob_day))

           return $cur_year-$dob_year;
       else
           return $cur_year-$dob_year-1;

SHOULD BE

if($cur_month>$dob_month || ($dob_month==$cur_month && $cur_day>$dob_day) )
           return $cur_year-$dob_year-1;
       else
           return $cur_year-$dob_year;

Correct me if I am mistaken...
squid at anime-sanctuary dot net
20-Mar-2005 04:57
A little function who calculate people age with their date of birth.
The format of date used is the one used in mysql table. (For example: 2004-10-23)

<?php
  
function CalcAge($date_of_birth) {
// YYYY-MM-DD
      
$cur_year=date("Y"
);
      
$cur_month=date("m"
);
      
$cur_day=date("d"
);           

      
$dob_year=substr($date_of_birth, 0, 4
);
      
$dob_month=substr($date_of_birth, 5, 2
);
      
$dob_day=substr($date_of_birth, 8, 2
);           
      
       if(
$cur_month>$dob_month || ($dob_month==$cur_month && $cur_day>=$dob_day
) )
           return
$cur_year-$dob_year
;
       else
           return
$cur_year-$dob_year-1
;
   }   
?>
duh_cabbage at paradise dot net dot nz
20-Mar-2005 03:41
I found this useful for working out the week of the year if you want to for example find the third Tuesday of the year, using the date("w") function could return 3 or 4 for the correct day. This function does not seem to count week one as the first 7 days of the year, but instead the first 4-7 days of the year, dependent on the start day of the year.

Using
<?php
$weekofyear
= (date("z", $stamp) - (date("z", $stamp)%7))/7 + 1
;
?>
seems to return the week number by counting each week through the day number of the year and counting 7 per week so week 1 is days 1-7, week 2 is days 8-14 etc.

Subtracting the remainder (date("z", $stamp)%7) tidies up the output by ensuring no decimals remain.
dzimi-21 at o2 dot pl
19-Mar-2005 10:34
Here is my way to count down to specified date:
<?
$end
= mktime(23,30,0,4,27,2005
);

$today= mktime(date("G"),date("i"
),
date("s"),date("m"),date("d"),date("Y"
));

$days=($end-$today)/86400
;
if (
$days>0
) {
$r1 = explode('.',$days
);
$hours=24*($days-$r1[0
]);
$r2 = explode('.',$hours
);
$minutes=60*($hours-$r2[0
]);
$r3 = explode('.',$minutes
);
$seconds=60*($minutes-$r3[0
]);
$r4 = explode('.',$seconds
);
echo
'Days left: ' .$r1[0
];
echo
'<br>Time left: ' . $r2[0] . ':' . $r3[0] . ':' . $r4[0
];
} else {
echo
"Matrix 4 is here:)"
;}
?>
roberta at lexi dot net
17-Mar-2005 01:18
Here's an easy way to deal with date recurrences, or if you need to add days, months or years to a current date... 

<?php
//$type determines which set of variables will be selected below.

if ($type == 'daily'){ 
//daily
  
$increment = 1
;
  
$stmt = 'days'
;
}
else if (
$type == 'weekly'){ 
//weekly
  
$increment = 7
;
  
$stmt = 'days'
;
}
else if (
$type == 'biweekly'){ 
//bi-weekly
  
$increment = 14
;
  
$stmt = 'days'
;
}
else if (
$type == 'monthly'){
//every month
  
$increment = 1
;
  
$stmt = 'months'
;
}
else if (
$type == 'biannualy'){
//every 6 months
  
$increment = 6
;
  
$stmt = 'months'
;
}
else{
//every year
  
$increment = 1
;
  
$stmt = 'years'
;
}
          
//set counter           
$t = $increment
;

//will continue to loop as many times as the recurrence ($number_times_recurring)       
while ($t<($number_times_recurring*$increment
)){
  
  
//$calendar_startdate and $calendar_enddate are pre-determined and match the Y-m-d H:i:s format
  
$startdate = date("Y-m-d H:i:s", strtotime($calendar_startdate." + ".$t." ".$stmt
));
  
$enddate = date("Y-m-d H:i:s", strtotime($calendar_enddate." + ".$t." ".$stmt
));
              
  
//here you can complete a database "INSERT" or whatever you want to do
  
  
$t = ($t+$increment
);
}
?>

I hope this helps! :)
Roberta
ardk at vfemail dot net
13-Mar-2005 07:09
A season checker (valid for Northern part of earth):

<?php
function SeasonCheck
()
{
   if (
date(M) == "Jan" || date(M) == "Dec" || date(M) == "Nov"
) {
       return
"w"
;
   }
   if (
date(M) == "Feb" || date(M) == "Mar" || date(M) == "Apr"
) {
       return
"s"
;
   }
   if (
date(M) == "May" || date(M) == "Jun" || date(M) == "Jul"
) {
       return
"m"
;
   }
   if (
date(M) == "Aug" || date(M) == "Sep" || date(M) == "Oct"
) {
       return
"a"
;
   }
}
?>
erik[at]phpcastle.com
16-Feb-2005 07:12
A little script that gives an array with periodes:

Example:
2005-01-01, 2005-01-02, 2005-01-03, 2005-01-04
  will be
2005-01-01, 2005-01-04

If you can work by periodes can this save some database space/speed.

Code:
<?php
  $previous_date
= ""
;
 
$periodes
= array();
 
$pointer = 0
;
  foreach (
$_POST['data'] as $key=>$value
){
   if (!empty(
$previous_date
))
     if (
floor(abs(strtotime($previous_date) - strtotime($value))/86400) == 1
){
      
$periodes[$pointer+1] = $value
;
     }
     else{
      
$pointer +=2
;
      
$periodes[$pointer] = $value
;
      
$periodes[$pointer+1] = $value
;
     }
   else {
    
$periodes[$pointer] = $value
;
    
$periodes[$pointer+1] = $value
;
   }
  
$previous_date = $value
;
  }
?>

The $periodes array will look like this:
[start_date],[end_date](,[start_date],[end_date])

Hope this code can help someone :) cheers
ktaufik(at)gmail(dot)com
16-Feb-2005 08:37
For you who works for localized "say" number to letter ( ex , 7=> seven, 8=>eight) for Bahasa Indonesia.

Indonesia "say" or "Terbilang" is based on 3 digit number.
thousands, millions and trillions .... will be based on the 3 digit number.

In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"

<?php
//build random 3 digit number to be "said" in Bahasa Indonesia
$x=rand(0,9
);
$y=rand(0,9
);
$z=rand(0,9
);

function
display_angka_bilangan($n
) {
  
$angka
= array(
    
1 => 'satu'
,
    
2 => 'dua'
,
    
3 => 'tiga'
,
    
4 => 'empat'
,
    
5 => "lima"
,
    
6 => 'enam'
,
    
7 => 'tujuh'
,
    
8 => 'delapan'
,
    
9 =>
'sembilan'
  
);
   return
$angka[$n
];
}
// Terbilang X-------Say X
if ($x==1){$terbilangx="seratus "
;}
elseif (
$x==0){$terbilangx=''
;}
else {
$terbilangx=''.display_angka_bilangan($x).' '.'ratus '
;}
// Terbilang Y ------Say Y
if ($y==0){$terbilangy=''
;}
elseif (
$y==1 && $z==1){$terbilangy="sebelas";$terbilangz=''
;}
elseif (
$y==1 && $z==0){$terbilangy="sepuluh ";$terbilangz=''
;}
elseif (
$y==1 && $z!==1 &&  $z!==0){$terbilangy=''.display_angka_bilangan($z).' belas '
;}
else {
$terbilangy=''.display_angka_bilangan($y).' '.'puluh '
;}
// Terbilang z ------Say z
if ($z==0){$terbilangz=""
;}
elseif (
$z==0 && $y==1){$terbilangz=""
;}
elseif (
$z==1 && $y==1){$terbilangz=""
;}
elseif(
$y==0) {$terbilangz="".display_angka_bilangan($z
);}
elseif (
$y==1 && $z!==1 &&  $z!==0) {$terbilangz=""
;}
else {
$terbilangz="".display_angka_bilangan($z
);};

$terbilang=$terbilangx.$terbilangy.$terbilangz
;
echo
$x.$y.$z." "
;
echo
$terbilang
;
?>

Hope it is useful
ktaufik(at)gmail(dot)com
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:

$test = date("F Y", mktime(0, 0, 0, 12, 0, 2005));

Will return November 2005, not December.

$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.

function weeks($year) {
   return date("W",mktime(0,0,0,12,28,$year));
}
Alex [AT] kosi2002 [COM]
26-Jan-2005 08:46
For lazy germans wanting to have a decent formatted
DateString printed, an example you can copy and paste - here, using the current time.
Prints out somthing like: Montag, den 14. Februar 2005
(My Birthday, hooray ;)

Et Voila:

<?php
//showing Dates in German lanuage:
 
function formatDateString($stamp
) {
    
//initalise String:
   //Gettting the months set up...
                
$monate = array(1=>"Januar"
,
                
2=>"Februar"
,
                
3=>"März"
,
                
4=>"April"
,
                
5=>"Mai"
,
                
6=>"Juni"
,
                
7=>"Juli"
,
                
8=>"August"
,
                
9=>"September"
,
                
10=>"Oktober"
,
                
11=>"November"
,
                
12=>"Dezember"
);
                
  
//Getting our Month
                
$monat = date("n", $stamp
);

    
//Getting the Days set up....
                
$tage = array("Sonntag","Montag","Dienstag","Mittwoch"
,
                    
"Donnerstag","Freitag","Samstag"
);

    
//Getting Day....
                  
$tag = date("w", $stamp
);
    

 
$printme = $tage[$tag].", den ".date("d", $stamp).". ".$monate[$monat]." ".date("Y", $stamp
);
 
 return
$printme
;
 }
 print
formatDateString(date(time
()));
 
?>

Thanx all for listening....
chris dot shepherd at gmail dot com
07-Jan-2005 05:04
The previous post about calculating age using the date function...

"chris dot shepherd at gmail dot com
27-Aug-2004 09:59
A nice way to calc age seeing that mktime only goes back until 1970 is to use the date function like this... "

There is a line of code I entered incorrectly

($monthdiff <= 0 && $daydiff < 0)

It should actually be

(($monthdiff < 0)  ||  ($monthdiff == 0 && $daydiff < 0))

The first example will be wrong when monthdiff is negative and daydiff is positive. For example current date is 01/06/2004 and dob is 03/02/1979. Whenever the monthdiff is negative we should always consider the condition true (we havent reached their bday yet) The original statement thinks the day matters when really the day only matters when we are in the month of our birth.
milad[at]rastian[dot]com
24-Dec-2004 09:40
All irainain who want use Jalali Date:
see this site :
http://jdf.farsiprojects.com
I create function such as date in php
rasmussens AT synergisminc DOT com
02-Dec-2004 06:56
This function allows you to determine the difference HH:MM:SS between two dates.  When you subtract timestamps and end up with small numbers Date() will return incorrect hours.  Only the minutes and seconds will be correct.  Of course 3600 would be Jan 1st 1970 1:00:00 am, but the problem is you still cant get the correct hours from Date() because it will convert it to a GMT time.  Here is a simple function so that you can return the time for smaller numbers:

<?
function GetTime ($timedifference
) {

   if (
$timedifference >= 3600
) {
      
$hval = ($timedifference / 3600
);
      
$hourtime = intval($hval
);

      
$leftoverhours = ($timedifference % 3600
);

      
$mval = ($leftoverhours / 60
);
      
$minutetime = intval($mval
);

      
$leftoverminutes = ($leftoverhours % 60
);
      
$secondtime = intval($leftoverminutes
);

      
$hourtime = str_pad($hourtime, 2, "0", STR_PAD_LEFT
);
      
$minutetime = str_pad($minutetime, 2, "0", STR_PAD_LEFT
);
      
$secondtime = str_pad($secondtime, 2, "0", STR_PAD_LEFT
);

       return
"$hourtime:$minutetime:$secondtime"
;
   }

   if (
$timedifference >= 60
) {

      
$hourtime = 0
;

      
$mval = ($timedifference / 60
);
      
$minutetime = intval($mval
);

      
$leftoverminutes = ($timedifference % 60
);
      
$secondtime = intval($leftoverminutes
);

      
$hourtime = str_pad($hourtime, 2, "0", STR_PAD_LEFT
);
      
$minutetime = str_pad($minutetime, 2, "0", STR_PAD_LEFT
);
      
$secondtime = str_pad($secondtime, 2, "0", STR_PAD_LEFT
);

       return
"$hourtime:$minutetime:$secondtime"
;
   }

  
  
$hourtime = 0
;
  
$minutetime = 0
;
   if (
$timedifference < 0 ) { $secondtime = 0
; }
   else {   
$secondtime = $timedifference
; }

  
$hourtime = str_pad($hourtime, 2, "0", STR_PAD_LEFT
);
  
$minutetime = str_pad($minutetime, 2, "0", STR_PAD_LEFT
);
  
$secondtime = str_pad($secondtime, 2, "0", STR_PAD_LEFT
);

   return
"$hourtime:$minutetime:$secondtime"
;
  
}

$mytime = GetTime(1101960767 - 1101961767
);
echo
$mytime
;

?>
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.

<?
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"
);
}
?>


출처 : http://cafe.naver.com/q69/9606
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함