시소당
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, rd나 th. 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 User Contributed Notes
date
stuff at rushsoft dot de
30-Jun-2005 05: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.
thinsoldier at thinsoldier ,com
23-Jun-2005 10:08
Because I hate having 50+ lines of html
whenever I want to add a day/month/year select box.
It allows defining of of name, id, class, width(css),
and selected value.
So, in my cms when adding a new entry it defaults to the current
date and when I'm editing a previous entry it defaults to the
date the entry was made
(after i explode the mysql date and assign each part to a variable)
-----------------------------------------
<p>Function for generating useful date select boxes</p>
adding something new, so that's today's date: <br>
Day: <? echo
$day_box=day_box('list_day', '', '', '155', date("d") ); ?> <br>
Month: <? echo
$month_box=month_box('list_month', '', '', '155', date("m") ); ?> <br>
Year: <? echo
$year_box=year_box('list_year', '', '', '100', date("Y") ); ?>
<p>Editing something old, so show it's original date pulled from the database or something</p>
Day: <? echo
$day_box=day_box('list_day', '', '', '155', 14 ); ?> <br>
Month: <? echo
$month_box=month_box('list_month', '', '', '155', 9 ); ?> <br>
Year: <? echo
$year_box=year_box('list_year', '', '', '100', 1992 ); ?>
<?
function day_box(
$name,
$id,
$class,
$width,
$selected)
{
$content='<select name="'.
$name.'" id="'.
$id.'" class="'.
$class.'" style="width:'.
$width.'px">'."\r";
for(
$i=1;
$i<=31;
$i++)
{
if(
$i ==
$selected) {
$isselected='selected'; } else {
$isselected='';}
$iki =
$i; if(
$iki<10){
$iki='0'.
$iki;}
$content.="\t<option value=\"
$iki\"
$isselected>";
$content.="
$iki</option>\r";
}
$content.="</select>";
return
$content;
}
////////////////////////////////////////
?>
<?
function month_box(
$name,
$id,
$class,
$width,
$selected)
{
$monthtext[1]="January";
$monthtext[2]="February";
$monthtext[3]="March";
$monthtext[4]="April";
$monthtext[5]="May";
$monthtext[6]="June";
$monthtext[7]="July";
$monthtext[8]="August";
$monthtext[9]="September";
$monthtext[10]="October";
$monthtext[11]="November";
$monthtext[12]="December";
$content='<select name="'.
$name.'" id="'.
$id.'" class="'.
$class.'" style="width:'.
$width.'px">'."\r";
for(
$i=1;
$i<=12;
$i++)
{
if(
$i ==
$selected) {
$isselected='selected'; } else {
$isselected='';}
$iki =
$i; if(
$iki<10){
$iki='0'.
$iki;}
$content.="\t<option value=\"
$iki\"
$isselected>";
$content.="
$iki -
$monthtext[
$i]</option>\r";
}
$content.="</select>";
return
$content;
}
////////////////////////////////////////
?>
<?
function year_box(
$name,
$id,
$class,
$width,
$selected)
{
$content='<select name="'.
$name.'" id="'.
$id.'" class="'.
$class.'" style="width:'.
$width.'px">'."\r";
for(
$i=1990;
$i<=2090;
$i++)
{
if(
$i ==
$selected) {
$isselected='selected'; } else {
$isselected='';}
$iki =
$i;
$content.="\t<option value=\"
$iki\"
$isselected>";
$content.="
$iki</option>\r";
}
$content.="</select>";
return
$content;
}
////////////////////////////////////////
?>
rtv84 at hotmail dot com
23-Jun-2005 07:49
A good week+year to timestamp/date function:
http://www.a-kok.com/php/datumundervecka.php
(Unfortunatly the explanation is written in Swedish).
ungu at terong dot com
23-Jun-2005 01: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());
?>
gummbahla AT msn.com
17-Jun-2005 06:42
Be carefull when using the W and Y option together!
The following example will print: 52-2006, instead of 1-2006 or 52-2005
<?
echo date('W-Y',mktime(0,0,0,1,1,2006));
?>
15-Jun-2005 12:28
There are certain advantages and disadvantages of passing the "dirty job" of formatting datestamps and timestamps to the database server itself, let say mysql. Formatting date/timestamps in the PHP script itself gives you more control in manipulating date and time without requiring another connection to the database to format the date/timestamp for you.
dancmdan at yahoo dot com
14-Jun-2005 07:18
I think you can get the same resul like Sunil Amber (sunil_ssm)
with date_format function of mysql .
Sunil code
Pdeudo Code
------------
$result = mysql_query("SELECT datetime, timestamp FROM log WHERE log_id = 1",
$conn);
$rs = mysql_fetch_array(
$result);
//e.g: 31-12-2005
$formatted_datetime = mysql_datetime(
$rs["datetime"],"d-m-Y");
//e.g: Sun, 31 December 2005
$formatted_timestamp = mysql_timestamp(
$rs["datetime"],"D,j F Y");
------------
Just modify your query like this
Pdeudo Code
------------
$result = mysql_query("SELECT date_format(datetime,'%d-%m-%Y') as formatted_datetime, date_format(timestamp,'%a,%e %M %Y') as formatted_timestamp FROM log WHERE log_id = 1",
$conn);
$rs = mysql_fetch_array(
$result);
//e.g: 31-12-2005
$formatted_datetime =
$rs["formatted_datetime"];
//e.g: Sun, 31 December 2005
$formatted_timestamp =
$rs["formatted_timestamp"];
------------
sunil_ssm at users dot sourceforge dot net
08-Jun-2005 09:51
The following function makes it easy for you to format mysql datetime and timestamp functions with a call of a function. This can be achieved with minimal coding as shown below.
Pdeudo Code
------------
$result = mysql_query("SELECT datetime, timestamp FROM log WHERE log_id = 1",
$conn);
$rs = mysql_fetch_array(
$result);
//e.g: 31-12-2005
$formatted_datetime = mysql_datetime(
$rs["datetime"],"d-m-Y");
//e.g: Sun, 31 December 2005
$formatted_timestamp = mysql_timestamp(
$rs["datetime"],"D,j F Y");
------------
function mysql_timestamp(
$stamp,
$format) {
$pattern = "/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/i";
if(preg_match(
$pattern,
$stamp,
$st) && checkdate(
$st[2],
$st[3],
$st[1])) {
return date(
$format, mktime(
$st[4],
$st[5],
$st[6],
$st[2],
$st[3],
$st[1]));
}
return
$stamp;
}
function mysql_datetime(
$datetime,
$format) {
$pattern = "/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/i";
if(preg_match(
$pattern,
$datetime,
$dt) && checkdate(
$dt[2],
$dt[3],
$dt[1])) {
return date(
$format, mktime(
$dt[4],
$dt[5],
$dt[6],
$dt[2],
$dt[3],
$dt[1]));
}
return
$datetime;
}
------------
Enjoy
Sunil Amber
http://jformmail.sourceforge.net/
witcho at gmail dot com
07-Jun-2005 12: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 11: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.
pmcdevitt(at)cesales.com
01-Jun-2005 07:14
It is important to note in the mktime() example that
$lastmonth doesn't always give you last months date. If you are on the 31st of a month and do:
$lastmonth=mktime(0,0,0,date("m")-1,date("d"),date("Y"));
the resulting day doesn't exist and rolls over to the next day. So if today is may 31st,
$lastmonth will equal may 1st, because april 31st does not exist. For my purposes all I need is the month so I check to see if date("d") = 31. If it does then I use:
$lastmonth=mktime(0,0,0,date("m")-1,date("d")-5,date("Y"));
$lastmonth= date("M",
$lastmonth);
You could subtract just one, but Februarys and leap years mess it up. 5 is just arbitrary.
moazzamk at gmail dot com
28-May-2005 11:57
this is a simple but helpful function i wrote for a project. it gives you the date of the previous day, for any given date.
<?php
class d{}
function get_prev_date(&
$d)
{
$ret = &new d();
if (
$d->month == 1 &&
$d->day == 1) {
$ret->day = 31;
$ret->month = 12;
$ret->year =
$d->year - 1;
return
$ret;
}
if (
$d->month == 3) { //for leap years and feb
if (
$d->day == 1 && date("L", mktime(0, 0, 0,
$d->month,
$d->day,
$d->year)) == 1)
$ret->day = 29;
else if (
$d->day == 1)
$ret->day = 28;
$ret->month = 2;
$ret->year =
$d->year ;
return
$ret;
}
if (
$d->day == 1) {
if (
$d->month == 5 ||
$d->month == 7 ||
$d->month == 8 ||
$d->month == 10
||
$d->month == 12)
$ret->day = 30;
else
$ret->day = 31;
$ret->month =
$d->month - 1;
$ret->year =
$d->year;
return
$ret;
}
$ret->day =
$d->day - 1;
$ret->month =
$d->month;
$ret->year =
$d->year;
return
$ret;
}
$d = &new d;
$d->day = 1;
$d->month = 3;
$d->year = 2004; //2004 was a leap year
$e = get_prev_date(
$d);
print
$e->year."-".
$e->month."-".
$e->day."\n";
Svein Tjonndal
26-May-2005 05:52
Since strtotime cannot handle future dates (like the year 2050), I use functions like the following to format dates.
Example of formatting date to French format:
function datefixFRENCH(
$mydate)
{
$day = substr(
$mydate,8,2);
$month = substr(
$mydate,5,2);
$year = substr(
$mydate,0,4);
$day = str_replace("0", "",
$day);
$month = str_replace("01", "Janvier",
$month);
$month = str_replace("02", "Février",
$month);
$month = str_replace("03", "Mars",
$month);
$month = str_replace("04", "Avril",
$month);
$month = str_replace("05", "Mai",
$month);
$month = str_replace("06", "Juin",
$month);
$month = str_replace("07", "Juillet",
$month);
$month = str_replace("08", "Août",
$month);
$month = str_replace("09", "Septembre",
$month);
$month = str_replace("10", "Octobre",
$month);
$month = str_replace("11", "Novembre",
$month);
$month = str_replace("12", "Décembre",
$month);
$mydate =
$day . ' ' .
$month . ' ' .
$year;
return
$mydate;
}
cdblog at gmail dot com
26-May-2005 05:00
<?php
/**
* @return void
* @desc with this function you can get how many weeks in the month.
* the resource's link is http://php.clickz.cn/articles/date/getWeekNum.html
* you can find the update version at my php blog: http://php.clickz.cn/
*/
function getWeekNum(
$year = 2005,
$month = 12) {
if (date("w",mktime(0,0,0,
$month,1,
$year)) > 4) {
if (checkdate(
$month,31,
$year) == true ) {
return 6;
} elseif (checkdate(
$month,31,
$year) == false ) {
if (checkdate(
$month,30,
$year) == false ) {
return 6;
} else {
return 5;
}
} else {
return 5;
}
} elseif ((date("w",mktime(0,0,0,
$month,1,
$year)) == 0) AND (
$month == 2) AND (checkdate(
$month,29,
$year) == false)) {
return 4;
} else {
return 5;
}
}
?>
nikhil at nikhilzkingdom dot com
26-May-2005 10:31
Function to display the current month calender as a table.
You can optionally change the
$year,
$month to which ever month you wish.Hope this helps
function displayCurrentMonthCalenderAsTable()
{
// Find the first day of the current month
$year=date("Y"); // this year
$month=date("n"); // this month
$day=1; // start from first of month
$month_caption=date("M
$year"); // caption to table
print "<table summary=\"Monthly calendar\">
<caption>
$month_caption</caption>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>\n";
$ts = mktime(0,0,0,
$month,
$day,
$year); // unix timestamp of the first day of current month
$weekday_first_day = date("w",
$ts); // which is the weekday of the first day of week 0-Sunday 6-Saturday
$slot=0;
print "<tr>\n"; // First row starts
for(
$i=0;
$i<
$weekday_first_day;
$i++) // Pad the first few rows(slots)
{
print " <td></td>"; // Empty slots
$slot++;
}
while(checkdate(
$month,
$day,
$year) &&
$date<32) // till there are valid days in current month
{
if(
$slot == 7) // if we moved past saturday
{
$slot = 0; // reset and move back to sunday
print "</tr>\n"; // end of this row
print "<tr>\n"; // move on to next row
}
echo " <td>
$day</td>"; // print the day
$day++;
$slot++;
}
if(
$slot>0) // have we started off a new last row
{
while(
$slot<7) // padding at the end to complete the last row table
{
print " <td></td>"; // empty slots
$slot++;
}
print "\n</tr>\n"; // close out last row
}
print '</table>'; //end of table
}
displayCurrentMonthCalenderAsTable();
yasingedikli at hotmail dot com
24-May-2005 08:46
You can get the beginn and end date from weeknumber !
function dateweek(
$weeknumber)
{
$x = strtotime("last Monday");
$Year = date("Y",
$x);
$Month = date("m",
$x);
$Day = date("d",
$x);
if (
$Month < 2 &&
$Day < 8) {
$Year =
$Year--;
$Month =
$Month--;
}
if (
$Month > 1 &&
$Day < 8)
$Month =
$Month--;
//DATE BEGINN OF THE WEEK ( Monday )
$Day =
$Day+7*
$weeknumber;
echo date('Y-m-d', mktime(0, 0, 0,
$Month,
$Day,
$Year));
//DATE END OF THE WEEK ( Sunday )
$Day =
$Day+6;
echo date('Y-m-d', mktime(0, 0, 0,
$Month,
$Day,
$Year));
}
// THIS WEEK
dateweek(0);
// LAST WEEK
dateweek(-1);
// NEXT WEEK
dateweek(1);
// 4 WEEK THEN
dateweek(4);
cmol at cmol dot dk
23-May-2005 02:01
This is how we do in denmark!..
<?PHP
function dato(
$time){
$d = date("j",
$time);
$m = date("n",
$time);
$y = date("Y",
$time);
$dnow = date("j");
$mnow = date("n");
$ynow = date("Y");
if (
$y ==
$ynow &&
$m ==
$mnow){
if(
$d ==
$dnow)
{
echo 'I dag kl. ';
echo date("G:i",
$time);
}
elseif(
$d ==
$dnow - 1)
{
echo 'I g岠kl. ';
echo date("G:i",
$time);
}
else
{
echo str_replace("May", "Maj", date('\D.j M - y',
$time));
}
}
else
{
echo str_replace("May", "Maj", date('\D.j M - y',
$time));
}
}
$time = time();
echo dato(
$time);
?>
searcher cookie dracon dot biz
22-May-2005 07: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
MG_Peter at o2 dot pl
20-May-2005 10:12
chris at zarkov dot co dot uk -> I know ;)
I've found it, while i tried to change the timezone in mysql timestamp!!! And didn't know how to manage date. Now, i know much more about php (but it's another story ;]).
easy timezone:
insert user timezone to the database you can use forms' <select> or something with values as signed short integers ('-1', or '5' i.e.)
example of my script...
<?php
include "database_connection.php";
$timezone =
$_REQUEST['timezone'];
$sql = mysql_query("UPDATE users SET timezone='
$timezone' WHERE user='
$_SESSION['username']'");
//here comes the error checking... simple if (!
$sql){echo "database error"; exit;}
?>
use user timezone from database.
<?php
$timezone =
$_sql_result['timezone']; //i.e. it can be '5' or '-5'
$user_date = date("d M Y H:i:s", (strtotime(
$your_row['lastlogin_date'])+
$timezone*3600))';
?>
memandeemail at gmail dot com
05-May-2005 01:52
//bugfixes
/**
* Return the Struct of days in week of the year
*
* @param int
$year
* @param string
$str1
* @param string
$str2
* @return array
*/
function weekstruct(
$year,
$str1 = "de",
$str2 = "ate") {
$result = array(); for (
$iC=1;
$iC <= 53;
$iC++)
$result[
$iC] = null;
$ults = -1;
for (
$dt = strtotime("
$year-01-01") ; date("Y",
$dt) ==
$year ;
$dt = strtotime("+1 day",
$dt)) {
if (date('W',
$dt) !=
$ults) {
//
$result[
$ults] .= " ".
$str2." ".date("d/m",strtotime("-1 day",
$dt));
$ults = date('W',
$dt);
$result[
$ults] =
$str1." ".date("d/m",
$dt)." ".
$str2." ".date("d/m",strtotime("Sunday",
$dt));
}
}
return
$result;
}
Vladimir Kornea of typetango.com
04-May-2005 11:34
$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 03: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));
}
chris at zarkov dot co dot uk
03-May-2005 06:48
MG_Peter at o2 dot pl - excellent way of converting datestamp to something English, works a treat :)
development at lab-9 dot com
02-May-2005 07:24
this function above takes date in format of YYYY-MM-DD (ex.: 2005-12-31) and checks, if this date is in the calendar
the first function just checks, if february has 29 or 28 days in the requested year.
<?php
function schaltjahr(
$jahr)
{
if(
$jahr % 400 == 0)
{ return true; }
else if(
$jahr % 4 == 0 &&
$jahr % 100 != 0)
{ return true; }
else
{ return false; }
}
function validate_date(
$temp)
{
$temp = explode('-',
$temp);
if(is_numeric(
$temp[0]))
{
if(
$temp[0] >= 1950)
{
if(is_numeric(
$temp[1]) &&
$temp[1] >= 1 &&
$temp[1] <= 12)
{
if(is_numeric(
$temp[2]) &&
$temp[2] >= 1)
{
if(
$temp[1] == 2)
{
// schaltjahr ??r />
$schaltjahr_days=28;
if(schaltjahr(
$temp[0]))
{
$schaltjahr_days = 29; }
if(
$temp[2] <=
$schaltjahr_days)
{
return true;
}
}
else
{
if(
$temp[1] >= 8)
{
$temp[1]++; }
if(
$temp[1] % 2 == 1)
{
if(
$temp[2] <= 31 &&
$temp[2] >= 1)
{
return true;
}
}
else if(
$temp[1] % 2 == 0)
{
if(
$temp[2] <= 30 &&
$temp[2] >= 1)
{
return true;
}
}
}
}
}
}
}
return false;
}
?>
MG_Peter at o2 dot pl
30-Apr-2005 08: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 08: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 04: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;
}
?>
jonathan at jkdwebmagic dot com
27-Apr-2005 12:48
Another version of the countdown:
// Event Date: 29 December 2005 - 14:35
$eventDateStamp = mktime(14, 35, 0, 12, 29, 2005);
if (
$eventDateStamp > time()) {
$secondsLeft =
$eventDateStamp - time();
$days = intval(
$secondsLeft / 86400); // 86400 seconds in a day
$partDay =
$secondsLeft - (
$days * 86400);
$hours = intval(
$partDay / 3600); // 3600 seconds in an hour
$partHour =
$partDay - (
$hours * 3600);
$minutes = intval(
$partHour / 60); // 60 seconds in a minute
$seconds =
$partHour - (
$minutes * 60);
$timeLeft =
$days." days ".
$hours." hours ".
$minutes." minutes ".
$seconds." seconds until event!!!";
} else {
$timeLeft = 'Event has come!!!';
}
echo
$timeLeft;
mk at se dot linux dot org
26-Apr-2005 09:16
here's a nice little function for checking if a date is valid:
<?php
function valid_date(
$d) {
return (
$d == date("Y-m-d", strtotime(
$d)));
}
?>
change the date format according to your needs.
aomairi at etech-systems dot com
24-Apr-2005 03:16
in order to insert date into MySQL database date function should be used this way:
$today = date("Y-m-d");
not using dashes in the function will result in inserting the date as zeros:0000-00-00
php at webparlour dot com
20-Apr-2005 08: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 09: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 12: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 01: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.
vinay at vinayras dot com
07-Apr-2005 03:19
For those who are looking for solutions to pre-1970 date issues ( on Windows) - Or with negative timestamps
This library will help.
http://phplens.com/phpeverywhere/adodb_date_library
bati1927 at msn dot com
06-Apr-2005 12: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 11: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;
}
glorin at hacnet dot ru
31-Mar-2005 05:53
echo
$date = '2005-03-31';
echo "\n";
print date("Y-m-d", strtotime("-4 month ".
$date));
echo "\n";
print date("Y-m-d", strtotime("-1 month ".
$date));
2005-03-31
2004-12-01
2005-03-03
djmaze(AT)cpgnuke(.)com
27-Mar-2005 02: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 01: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 01: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 05: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 11: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
19-Mar-2005 10: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 05: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
16-Mar-2005 08: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 02: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";
}
}
?>
mgyth'at'online'dot'no
12-Mar-2005 03:15
I made a simple, not accurate but working way of counting down in days to a target date.
For simplicity it assumes a 365 day year and a 30 day month.
<?php
/*---Input Target day of month---*/
$day = '28' - date("d");
/*---Input Target month of year---*/
$month = '08' - date("m");
/*---Input Target year---*/
$year = '05' - date("y");
/*---And then we cheat a bit, it's only an approximate date---*/
if (
$day <= '0'){
$month =
$month - '1';
$day =
$day + '30';
}
/*---The math for the number of days are easy---*/
$total = (
$year * '365') + (
$month * '30') +
$day;
/*---And then we echo it for your viewing pleasure---*/
echo 'I\'ll be a dad in: '.
$total.' days!';
?>
erik[at]phpcastle.com
16-Feb-2005 02: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 03: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 11: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 10: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 03: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 12: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.
mike at NOSPAM dot markley dot org
31-Dec-2004 04:34
Regarding timezone handling:
Adding 5 to the current hour for Eastern is great, but then you have to deal with daylight savings and know the GMT offset for anything you want to support.
However, PHP running as a module under Apache (at least on *NIX; YMMV on Windows) will obey the TZ environment variable, which can be set with putenv(). Any timezone your server supports can be put into that variable, so you can do any of the following:
putenv('TZ=EST5EDT');
putenv('TZ=US/Eastern');
putenv('TZ=America/New_York');
date() will then convert the time for you, and the T and Z formats will give back the right information, too.
milad[at]rastian[dot]com
24-Dec-2004 04: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 01: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;
?>
val at valcohen dot com
02-Nov-2004 07:56
I was going crazy trying to read the table above -- alpha
sorting by option scatters similar formats all over the place.
So, I grouped the format characters by the part of the
timestamp they return. Enjoy!
Fmt Description
DAY ===========================================================
d Day of the month, 2 digits with leading zeros
D A textual representation of a day, three letters
j Day of the month without leading zeros
l A full textual representation of the day of the week
S English ordinal suffix for the day of the month, 2 characters
w Numeric representation of the day of the week
z The day of the year (starting from 0)
WEEK ==========================================================
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
MONTH =========================================================
F A full textual representation of a month, such as January or March
m Numeric representation of a month, with leading zeros
M A short textual representation of a month, three letters
n Numeric representation of a month, without leading zeros
t Number of days in the given month
YEAR ==========================================================
L Whether it's a leap year
Y A full numeric representation of a year, 4 digits
y A two digit representation of a year
TIME ==========================================================
a Lowercase Ante meridiem and Post meridiem
A Uppercase Ante meridiem and Post meridiem
B Swatch Internet time
g 12-hour format of an hour without leading zeros
G 24-hour format of an hour without leading zeros
h 12-hour format of an hour with leading zeros
H 24-hour format of an hour with leading zeros
i Minutes with leading zeros
s Seconds, with leading zeros
TIMEZONE ======================================================
I Whether or not the date is in daylights savings time
O Difference to Greenwich time (GMT) in hours
T Timezone setting of this machine
Z Timezone offset in seconds. Zones west of UTC are negative, east are positive.
FULL DATETIME =================================================
c ISO 8601 date (added in PHP 5)
r RFC 2822 formatted date
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
jacQues at imperium dot be
27-Oct-2004 09:30
The 'z' option is indeed 1..365 and does NOT take into account leap days... if you want to know the TRUE day number, use:
$realday = date('z')+(date('L') and date('m')>2? 1: 0);
jacQues
php at document-root dot de
14-Apr-2004 01: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 05: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");
}
?>
aceh at bitex dot bg
21-Jan-2004 07:49
This is a function that converts the integer part of Delphi TDate (days passed from 30/12/1899) to Unix Timestamp. Hope it can be useful.
<?php
function DelphiDate2UnixTimestamp(
$delphi_date){
//delphi date is days passed from 30/12/1899
//unix timestamps start from 1/1/1970 = 25569
$UNIX_FIRST_DATE=25569; //1/1/1970 in Delphi
$days=
$delphi_date-
$UNIX_FIRST_DATE;
if (
$days<0){
$days=0;
}
return strtotime("1 January 1970 +
$days days");
}
?>
jenz at mail dot de
02-Nov-2003 09:29
My problem was to convert the 18digit timestamps from an
active directory LDAP server to a unix timestamp.
the win32 timestamp occurs for example in the lastlogon entry of the ADS.
The time is measured in Win32 epoch beginning in the year 1601. Ticks are in 100nanoseconds.
Reference: http://xml-x.org/time.html#time
I wrote the following simple function:
function win2unix(
$date_string,
$date_timestamp)
{
$epoch_diff = 11644473600; // difference 1601<>1970 in seconds. see reference URL
$date_timestamp =
$date_timestamp * 0.0000001;
$unix_timestamp =
$date_timestamp -
$epoch_diff;
echo date(
$date_string,
$unix_timestamp);
}
Now it display me the correct date.
rafaelr at veloxmail dot com dot br
17-Oct-2003 11:03
To convert from day/month/year to year/month/day (as for MySQL), try this one-liner:
<?php
$date_mysql = implode( '-', array_reverse( explode( '/', '20/10/2003' ) ) ); ?>
I hope it helps!
devinemke at yahoo dot com
07-Jun-2002 12:49
The "T" argument to the date() function displays timezone. The actual formatting appears to be OS dependent. On my Win32 machine it displays "Eastern Standard Time" and my UNIX server shows "EST".