|
|
 |
XIX. Date and Time Functions
These functions allow you to get the date and time from the server
where your PHP scripts are running. You can use these functions to format the
date and time in many different ways.
Note:
Please keep in mind that these functions are dependent on
the locale settings of your server. Make sure to take
daylight saving time (use e.g.
$date = strtotime('+7 days', $date) and not
$date += 7*24*60*60)
and leap years into consideration when working
with these functions.
No external libraries are needed to build this extension. There is no installation needed to use these
functions; they are part of the PHP core. This extension has no configuration directives defined in php.ini. This extension has no resource types defined. This extension has no constants defined. - Table of Contents
- checkdate -- Validate a Gregorian date
- date_sunrise --
Returns time of sunrise for a given day and location
- date_sunset --
Returns time of sunset for a given day and location
- date -- Format a local time/date
- getdate -- Get date/time information
- gettimeofday -- Get current time
- gmdate -- Format a GMT/UTC date/time
- gmmktime -- Get Unix timestamp for a GMT date
- gmstrftime -- Format a GMT/UTC time/date according to locale settings
- idate -- Format a local time/date as integer
- localtime -- Get the local time
- microtime -- Return current Unix timestamp with microseconds
- mktime -- Get Unix timestamp for a date
- strftime -- Format a local time/date according to locale settings
- strptime --
Parse a time/date generated with strftime()
- strtotime -- Parse about any English textual datetime description into a Unix timestamp
- time -- Return current Unix timestamp
User Contributed Notes
Date and Time Functions
r00t_ at mail dot ru
06-May-2005 03:33
Function generate one month calendar like
February
Mon Tue Wed Thu Fri Sat Sun
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
(default in russian locale)
<?php
$year = (int)$_GET["year"];
$month = (int)$_GET["month"];
draw_month_cal($year, $month);
function draw_month_cal($year, $month, $locale = array ('ru_RU.CP1251', 'rus_RUS.1251'))
{
if (checkdate($month, 1, $year) && setlocale (LC_TIME, $locale)) {
if (!$day = date("w", $f_day = mktime(0, 0, 0, $month, 1, $year)))
$day = 7; print "<table border=0><tr><th colspan=7>" . strftime("%B", $f_day) . "</td></tr><tr>"; for ($i = 8; --$i;)
print "<th>" . strftime("%a", mktime(0, 0, 0, $month, 16 - $i - $day, $year)) . "</th>"; print "</tr><tr>" . str_repeat("<td></td>", --$day); while (checkdate($month, ++$i, $year)) { print "<td>$i</td>";
if (!(++$day % 7)) print "</tr><tr>"; }
print "</tr></table>";
}
}
?>
info at programare dot org
05-May-2005 01:34
A simple DateAdd() function:
function DateAdd($v,$d=null , $f="d/m/Y"){
$d=($d?$d:date("Y-m-d"));
return date($f,strtotime($v." days",strtotime($d)));
}
Then use it:
echo DateAdd(2); // 2 days after
echo DateAdd(-2,0,"Y-m-d"); // 2 days before with gigen format
echo DateAdd(3,"01/01/2000"); // 3 days after given date
matando on xs4all dot nl
31-Mar-2005 03:17
You might want to add that the DATEDIFF function was added in MySQL 4.1.1. thus most hosts will not support this as I write this.
datavortex at gmail dot com
18-Mar-2005 06:19
This is a litttle function I cobbled together from my own code, and snippets from this site to calculate the difference between two datetimes without having to confine it to simply one interval. This will tell you how many weeks, days, hours, minutes, and seconds there are between the given datetimes, and also makes a little English string you can use.
This could easily be expanded to include months, and years, but I didn't want to have to deal with any of the leap year and variable month length stuff.
<?
function dateDiff($dateTimeBegin,$dateTimeEnd) {
$dateTimeBegin =strtotime($dateTimeBegin);
$dateTimeEnd =strtotime($dateTimeEnd);
if($dateTimeEnd === -1 || $dateTimeBegin === -1) {
return false;
}
$diff = $dateTimeEnd - $dateTimeBegin;
if ($diff < 0) {
return false;
}
$weeks = $days = $hours = $minutes = $seconds = 0; if($diff % 604800 > 0) {
$rest1 = $diff % 604800;
$weeks = ($diff - $rest1) / 604800; if($rest1 % 86400 > 0) {
$rest2 = ($rest1 % 86400);
$days = ($rest1 - $rest2) / 86400; if( $rest2 % 3600 > 0 ) {
$rest3 = ($rest2 % 3600);
$hours = ($rest2 - $rest3) / 3600; if( $rest3 % 60 > 0 ) {
$seconds = ($rest3 % 60);
$minutes = ($rest3 - $seconds) / 60; } else {
$minutes = $rest3 / 60;
}
} else {
$hours = $rest2 / 3600;
}
} else {
$days = $rest1/ 86400;
}
}else {
$weeks = $diff / 604800;
}
$string = array();
if($weeks > 1) {
$string[] = "$weeks weeks";
} elseif ($weeks == 1) {
$string[] = "a week";
}
if($days > 1) {
$string[] = "$days days";
} elseif($days == 1) {
$string[] = "a day";
}
if($hours > 1) {
$string[] = "$hours hours";
} elseif ($hours == 1) {
$string[] = "an hour";
}
if($minutes > 1) {
$string[] = "$minutes minutes";
} elseif ($minutes == 1) {
$string[] = "a minute";
}
if($seconds > 1) {
$string[] = "$seconds seconds";
} elseif($seconds == 1) {
$string[] = "a second";
}
$text = join(', ', array_slice($string,0,sizeof($string)-1)) . ", and ";
$text .= array_pop($string); return array($text, $weeks, $days, $hours, $minutes, $seconds);
?>
JMPZ art JMPZ dort ORG
03-Mar-2005 11:31
If you are dealing with a date in a database, you could just use the mysql function DATEDIFF(expr1,expr2) To calculate the difference without big bulky php functions.
andreencinas at yahoo dot com dot br
18-Jan-2005 11:56
//function like dateDiff Microsoft
//bug update for previous
function dateDiff($interval,$dateTimeBegin,$dateTimeEnd) {
//Parse about any English textual datetime
//$dateTimeBegin, $dateTimeEnd
$dateTimeBegin=strtotime($dateTimeBegin);
if($dateTimeBegin === -1) {
return("..begin date Invalid");
}
$dateTimeEnd=strtotime($dateTimeEnd);
if($dateTimeEnd === -1) {
return("..end date Invalid");
}
$dif=$dateTimeEnd - $dateTimeBegin;
switch($interval) {
case "s"://seconds
return($dif);
case "n"://minutes
return(floor($dif/60)); //60s=1m
case "h"://hours
return(floor($dif/3600)); //3600s=1h
case "d"://days
return(floor($dif/86400)); //86400s=1d
case "ww"://Week
return(floor($dif/604800)); //604800s=1week=1semana
case "m": //similar result "m" dateDiff Microsoft
$monthBegin=(date("Y",$dateTimeBegin)*12)+
date("n",$dateTimeBegin);
$monthEnd=(date("Y",$dateTimeEnd)*12)+
date("n",$dateTimeEnd);
$monthDiff=$monthEnd-$monthBegin;
return($monthDiff);
case "yyyy": //similar result "yyyy" dateDiff Microsoft
return(date("Y",$dateTimeEnd) - date("Y",$dateTimeBegin));
default:
return(floor($dif/86400)); //86400s=1d
}
}
andreencinas at yahoo dot com dot br
17-Jan-2005 12:20
function dateDiff($type,$dateTimeBegin,$dateTimeEnd) {
//Analisa qualquer descriçمo em texto em inglês de data hora em timestamp Unix
if($type!="d" && $type!="m" && $type!="y") {
return("..type Invalid");
}
$dateTimeBegin=strtotime($dateTimeBegin);
if($dateTimeBegin === -1) {
return("..begin date Invalid");
}
$dateTimeEnd=strtotime($dateTimeEnd);
if($dateTimeEnd === -1) {
return("..end date Invalid");
}
switch($type) {
case "d":
$dif=$dateTimeEnd - $dateTimeBegin;
//86400 24horas
return(floor($dif / 86400));
case "m":
$anosTransc=date("Y",$dateTimeEnd) - date("Y",$dateTimeBegin);
$mesesTransc=date("n",$dateTimeEnd) - date("n",$dateTimeBegin);
//transformando o sinal
if($mesesTransc<0) {$mesesTransc=$mesesTransc-($mesesTransc*2);}
return(($anosTransc*12) + $mesesTransc);
case "y":
return(date("Y",$dateTimeEnd) - date("Y",$dateTimeBegin));
default:
$dif=$dateTimeEnd - $dateTimeBegin;
//86400 24horas
return(floor($dif / 86400));
}
}
Elizalde Baguinon
07-Jan-2005 09:46
I evaluated the modified version of Xiven's datediff (below) and I saw some errors. I switched the lines of getting the seconds and the formatting of date. I was testing the datediff() function with a "d" interval. Here I added my test code.
$dateA = "2004-12-31";
$dateB = "2005-01-01";
function datediff($interval, $date1, $date2) {
// Function roughly equivalent to the ASP "DateDiff" function
/* Get the seconds first */
$seconds = strtotime($date2) - strtotime($date1);
$date1=date("Y-m-d", strtotime($date1));
$date2=date("Y-m-d",strtotime($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":
/* parses the year, month and days. split() was replaced with explode(), PHP Manual says it's faster */
list($year1, $month1, $day1) = explode('-', $date1);
list($year2, $month2, $day2) = explode('-',$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 the +ve integer only
if ($diff<0){
$diff=0-$diff;
}
return $diff;
}
echo "x: $dateA<br>";
echo "y: $dateB<br>";
echo "<br>";
echo datediff ("d",$dateA, $dateB);
Ruby
06-Jan-2005 11:09
just modified from Xiven
function datediff($interval, $date1, $date2) {
// Function roughly equivalent to the ASP "DateDiff" function
//set the date format first
$date1= date("Y-m-d", strtotime($date1));
$date2= date("Y-m-d",strtotime($date2));
$seconds = $date2 - $date1;
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 the +ve integer only
if ($diff <0)
{
$diff= 0-$diff;
}
return $diff;
}
mincklerstraat at softhome dot net
11-Oct-2004 04:43
charles at etherscapes dot com
04-Jun-2004 07:54
There are two dates that I know of that produce an incorrect result for the date functions above: 2004-04-04 and 2004-04-05. The days difference is zero instead of one.
jens at jebecs dot de
03-Jun-2004 07:29
There is an error in vincentv's post from 07-Feb-2001 11:23:
In function dayDiff(..) the return statement must be replaced by:
<?
return ( (getYear($timestamp1)*365 + $dayInYear1) -
(getYear($timestamp2)*365 + $dayInYear2) );
?>
nickaubert at america's biggest isp dot com
12-Apr-2004 04:13
I ran into an issue using a function that loops through an array of dates where the keys to the array are the Unix timestamp for midnight for each date. The loop starts at the first timestamp, then incremented by adding 86400 seconds (ie. 60 x 60 x 24). However, Daylight Saving Time threw off the accuracy of this loop, since certain days have a duration other than 86400 seconds. I worked around it by adding a couple of lines to force the timestamp to midnight at each interval.
<?php
$ONE_DAY = 90000; for ( $each_timestamp = $start_time ; $each_timestamp <= $end_time ; $each_timestamp += $ONE_DAY) {
$this_timestamp_array = getdate( $each_timestamp );
$each_timestamp = mktime ( 0 , 0 , 0 , $this_timestamp_array[mon] , $this_timestamp_array[mday] , $this_timestamp_array[year] );
}
?>
pk_jsp at rediffmail dot com
12-Apr-2004 03:06
Just want to add a comment to the function datediff given by Xiven that simple difference of 2 dates as in
$seconds = $date2 - $date1; will nor work instead the following need to be used.
$seconds = strtotime($date2) - strtotime($date1);
scott_webster_2000 at yahoo dot com
20-Feb-2004 01:02
Here is a slight improvement over wwb_99@yahoo's entry. (It works now.)
function date_diff($earlierDate, $laterDate) {
//returns an array of numeric values representing days, hours, minutes & seconds respectively
$ret=array('days'=>0,'hours'=>0,'minutes'=>0,'seconds'=>0);
$totalsec = $laterDate - $earlierDate;
if ($totalsec >= 86400) {
$ret['days'] = floor($totalsec/86400);
$totalsec = $totalsec % 86400;
}
if ($totalsec >= 3600) {
$ret['hours'] = floor($totalsec/3600);
$totalsec = $totalsec % 3600;
}
if ($totalsec >= 60) {
$ret['minutes'] = floor($totalsec/60);
}
$ret['seconds'] = $totalsec % 60;
return $ret;
}
php at sarge dot ch
28-Jan-2004 07:58
Additional thisone here (didn't test it yet but should work :D):
<?php
function dateDifference($start_timestamp,$end_timestamp,$unit= 0){
$days_seconds_star= (23 * 56 * 60) + 4.091; $days_seconds_sun= 24 * 60 * 60; $difference_seconds= $end_timestamp - $start_timestamp;
switch($unit){
case 3: $difference_days= round(($difference_seconds / $days_seconds_sun),2);
return 'approx. '.$difference_hours.' Days';
case 2: $difference_hours= round(($difference_seconds / 3600),2);
return 'approx. '.$difference_hours.' Hours';
break;
case 1: $difference_minutes= round(($difference_seconds / 60),2);
return 'approx. '.$difference_minutes.' Minutes';
break;
default: if($difference_seconds > 1){
return $difference_seconds.' Seconds';
}
else{
return $difference_seconds.' Second';
}
}
}
?>
wwb_99 at yahoo dot com
25-Jan-2004 04:12
Handy little function getting the total difference in dates.
function DateDiff($tfirst, $tsecond)
{
//returns an array with numeric values for in an array measuring days, hours, minutes & seconds
$ret=array();
$totalsec=$tsecond-$tfirst;
$ret['days']=round(($totalsec/86400));
$totalsec=$totalsec % 86400;
$ret['hours']=round(($totalsec/3600));
$totalsec=$totalsec % 3600;
$ret['minutes']=round(($totalsec/60));
$ret['seconds']=$totalsec % 60;
return $ret;
}
php at elmegil dot net
20-Dec-2003 01:40
A much easier way to do days diff is to use Julian Days from the Calendar functions:
$start = gregoriantojd($smon, $sday, $syear);
$end = gregoriantojd($emon, $eday, $eyear);
$daysdiff = $end - $start;
You can see the obvious ways to wrap a function around that.
vincentv at thevoid dot demon dot nl
19-Nov-2003 04:56
A rectification to the some of the functions i posted a while ago.
They do not work correctly under all circumstances (in my small test cases they worked) which is due to the fact that when you create a date using mktime, which returns a certain amount of seconds, this is not valid for every month since each month has a different amount of seconds.
The solution is to break up the original timestamp, add to it's seperate parts and create a new timestamp.
Old:
=====
function sub($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
$mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
return $timestamp - $mytime;
}
function add($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
$mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
return $timestamp + $mytime;
}
=====
New:
=====
function add($timestamp, $seconds, $minutes, $hours, $days, $months, $years) {
$timePieces = getdate($timestamp);
return mktime( $timePieces["hours"] + $hours,
$timePieces["minutes"] + $minutes,
$timePieces["seconds"] + $seconds,
$timePieces["mon"] + $months,
$timePieces["mday"] + $days,
$timePieces["year"] + $years );
}
function sub($timestamp, $seconds, $minutes, $hours, $days, $months, $years) {
$timePieces = getdate($timestamp);
return mktime( $timePieces["hours"] - $hours,
$timePieces["minutes"] - $minutes,
$timePieces["seconds"] - $seconds,
$timePieces["mon"] - $months,
$timePieces["mday"] - $days,
$timePieces["year"] - $years );
}
=====
Regards,
- Vincent
CodeDuck at gmx dot net
07-Nov-2003 09:30
in reply to dkan at netscreen dot com 29-Aug-2003 07:40
> Zero-padding is easier to read and less complicated if you
> use the substr() function instead of an if-then statement.
my two versions of printtime with padding:
<?
function printtime() {
$timenow = getdate();
printf(
'%02d %02d %02d',
$timenow["hours"],
$timenow["minutes"],
$timenow["seconds"]
);
}
?>
or the better one:
<?
function printtime() {
echo date('H i s');
}
?>
Xiven
02-Oct-2003 09:09
One thing PHP really lacks IMHO is an equivalent of ASP's "DateDiff" function. Here's a function that comes close to duplicating the functionality:
<?php
function datediff($interval, $date1, $date2) {
$seconds = $date2 - $date1;
switch($interval) {
case "y":
list($year1, $month1, $day1) = split('-', date('Y-m-d', $date1));
list($year2, $month2, $day2) = split('-', date('Y-m-d', $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('-', date('Y-m-d', $date1));
list($year2, $month2, $day2) = split('-', date('Y-m-d', $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":
$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;
}
?>
dkan at netscreen dot com
29-Aug-2003 04:40
Zero-padding is easier to read and less complicated if you use the substr() function instead of an if-then statement.
function printtime() {
$timenow = getdate();
$hours = substr("0" . $timenow["hours"], -2);
$minutes = substr("0" . $timenow["minutes"], -2);
$seconds = substr("0" . $timenow["seconds"], -2);
print($hours . " " . $minutes . " " . $seconds);
}
bitbuster at example dot com
24-Jul-2003 11:01
If you have to compare timestamps, I suggest you do it inside the database.. postgres, for example, allows statements like this:
select (current_timestamp < (select zeitdatum from time_test where zahl=5) );
menaurus at gmx dot de
16-Jul-2003 07:37
The argument has to be in the standard mysql format (y-m-d)...
function age($date) {
if (!$date) return false;
$year=0+substr($date,0,4);
$month=0+substr($date,5,2);
$day=0+substr($date,8,2);
$t=0;
$d=date("d");
$m=date("m");
$y=date("Y");
$age=$y-$year;
if ($m<$month) $t=-1;
else if ($m==$month) if ($d<$day) $t=-1;
return ($age+$t);
}
this funktion has got a little bug:
On Line 12 and 13...
Bugfix:
12 if ($month<$m) $t=-1;
13 else if ($m==$month AND $day<$d) $t=-1;
you NOSPAM don't need 2 know ETC
24-Mar-2003 10:17
EXCEL DATES TO UNIX TIMESTAMPS
----------------------------
I get a lot of dates which are sent to me in those dastardly Excel spreadsheet things. For example, the date 15 April 1976, Excel stores as 27865.
I convert these to UNIX timestamps using the little function below.
<?
function xl2timestamp($xl_date)
{
$timestamp = ($xl - 25569) * 86400;
return $timestamp;
}
?>
garyc at earthling dot net
18-Mar-2003 11:08
I needed to calculate the week number from a given date and vice versa, where the week starts with a Monday and the first week of a year may begin the year before, if the year begins in the middle of the week (Tue-Sun). This is the way weekly magazines calculate their issue numbers.
Here are two functions that do exactly that:
Hope somebody finds this useful.
Gary
/* w e e k n u m b e r -------------------------------------- //
weeknumber returns a week number from a given date (>1970, <2030)
Wed, 2003-01-01 is in week 1
Mon, 2003-01-06 is in week 2
Wed, 2003-12-31 is in week 53, next years first week
Be careful, there are years with 53 weeks.
// ------------------------------------------------------------ */
function weeknumber ($y, $m, $d) {
$wn = strftime("%W",mktime(0,0,0,$m,$d,$y));
$wn += 0; # wn might be a string value
$firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
if ($firstdayofyear["wday"] != 1) # if 1/1 is not a Monday, add 1
$wn += 1;
return ($wn);
} # function weeknumber
/* d a t e f r o m w e e k ---------------------------------- //
From a weeknumber, calculates the corresponding date
Input: Year, weeknumber and day offset
Output: Exact date in an associative (named) array
2003, 12, 0: 2003-03-17 (a Monday)
1995, 53, 2: 1995-12-xx
...
// ------------------------------------------------------------ */
function datefromweek ($y, $w, $o) {
$days = ($w - 1) * 7 + $o;
$firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
if ($firstdayofyear["wday"] == 0) $firstdayofyear["wday"] += 7;
# in getdate, Sunday is 0 instead of 7
$firstmonday = getdate(mktime(0,0,0,1,1-$firstdayofyear["wday"]+1,$y));
$calcdate = getdate(mktime(0,0,0,$firstmonday["mon"], $firstmonday["mday"]+$days,$firstmonday["year"]));
$date["year"] = $calcdate["year"];
$date["month"] = $calcdate["mon"];
$date["day"] = $calcdate["mday"];
return ($date);
} # function datefromweek
balin
16-Feb-2003 04:23
this function count days between $start and $end dates in mysql format (yyyy-mm-dd)
if one of paramters is 0000-00-00 will return 0
$start date must be less then $end
<?
function count_days($start, $end)
{
if( $start != '0000-00-00' and $end != '0000-00-00' )
{
$timestamp_start = strtotime($start);
$timestamp_end = strtotime($end);
if( $timestamp_start >= $timestamp_end ) return 0;
$start_year = date("Y",$timestamp_start);
$end_year = date("Y", $timestamp_end);
$num_days_start = date("z",strtotime($start));
$num_days_end = date("z", strtotime($end));
$num_days = 0;
$i = 0;
if( $end_year > $start_year )
{
while( $i < ( $end_year - $start_year ) )
{
$num_days = $num_days + date("z", strtotime(($start_year + $i)."-12-31"));
$i++;
}
}
return ( $num_days_end + $num_days ) - $num_days_start;
}
else
{
return 0;
}
}
?>
jlim at natsoft dot com dot my
26-Jan-2003 04:28
zan at stargeek dot com
24-Jan-2003 12:49
brighn (a) yahoo (.) com
03-Jan-2003 12:46
I needed a function that determined the last Sunday of the month. Since it's made for the website's "next meeting" announcement, it goes based on the system clock; also, if today is between Sunday and the end of the month, it figures out the last Sunday of *next* month. lastsunday() takes no arguments and returns the date as a string in the form "January 26, 2003". I could probably have streamlined this quite a bit, but at least it's transparent code. =)
/* The two functions calculate when the next meeting will
be, based on the assumption that the meeting will be on
the last Sunday of the month. */
function getlast($mon, $year) {
$daysinmonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
$days = $daysinmonth[$mon-1];
if ($mon == 2 && ($year % 4) == 0 && (($year % 100) != 0 ||
($year % 400) == 0)) $days++;
if ($mon == 2 && ($year % 4) == 0 && ($year % 1000) != 0) $days++;
$lastday = getdate(mktime(0,0,0,$mon,$days,$year));
$wday = $lastday['wday'];
return getdate(mktime(0,0,0,$mon,$days-$wday,$year));
}
function lastsunday() {
$today = getdate();
$mon = $today['mon'];
$year = $today['year'];
$mday = $today['mday'];
$lastsun = getlast($mon, $year);
$sunday = $lastsun['mday'];
if ($sunday < $mday) {
$mon++;
if ($mon = 13) {
$mon = 1;
$year++;
}
$lastsun = getlast($mon, $year);
$sunday = $lastsun['mday'];
}
$nextmeeting = getdate(mktime(0,0,0,$mon,$sunday,$year));
$month = $nextmeeting['month'];
$mday = $nextmeeting['mday'];
$year = $nextmeeting['year'];
return "$month $mday, $year";
}
visualmind at php dot net
25-Dec-2002 03:49
Here's a new function for Hejri (Hijri) date conversion, It has a better flawless calculation than the previous posted function and it's implemented to be an official alternative for the php DATE function which returns Arabic Translated date and optionally Hejri converted.
Note: to view arabic titles correctly change view-encoding to Arabic-Windows (windows-1256)
function arabicDate($format, $timestamp) {
/*
written by Salah Faya (visualmind@php.net) http://www.php4arab.info/scripts/arabicDate
$format:
[*]hj|ar|en:[jdl][Fmn][Yy][Aa] (php.date function handles the rest chars)
* will add <span dir=rtl lang=ar-sa>..</span>
examples:
echo arabicDate('hj:l d-F-Y هـ', time());
echo arabicDate('ar:l d/F - h:iA', time());
*/
$format=trim($format);
if (substr($format,0,1)=='*') {
$use_span=true;
$format=substr($format,1);
} else $use_span=false;
$type=substr($format,0,3);
$arDay = array("Sat"=>"السبت", "Sun"=>"الأحد", "Mon"=>"الإثنين", "Tue"=>"الثلاثاء",
"Wed"=>"الأربعاء", "Thu"=>"الخميس", "Fri"=>"الجمعة");
$ampm=array('am'=>'صباحا','pm'=>'مساء');
list($d,$m,$y,$dayname,$monthname,$am)=explode(' ',date('d m Y D M a', $timestamp));
if ($type=='hj:') {
if (($y>1582)||(($y==1582)&&($m>10))||(($y==1582)&&($m==10)&&($d>14))) {
$jd=ard_int((1461*($y+4800+ard_int(($m-14)/12)))/4);
$jd+=ard_int((367*($m-2-12*(ard_int(($m-14)/12))))/12);
$jd-=ard_int((3*(ard_int(($y+4900+ard_int(($m-14)/12))/100)))/4);
$jd+=$d-32075;
} else {
$jd = 367*$y-ard_int((7*($y+5001 + ard_int(($m-9)/7)))/4) + ard_int((275*$m)/9)+$d+1729777;
}
$l=$jd-1948440+10632;
$n=ard_int(($l-1)/10631);
$l=$l-10631*$n+355; // Correction: 355 instead of 354
$j=(ard_int((10985-$l)/5316)) * (ard_int((50*$l)/17719)) + (ard_int($l/5670)) * (ard_int((43*$l)/15238));
$l=$l-(ard_int((30-$j)/15)) * (ard_int((17719*$j)/50)) - (ard_int($j/16)) * (ard_int((15238*$j)/43))+29;
$m=ard_int((24*$l)/709);
$d=$l-ard_int((709*$m)/24);
$y=30*$n+$j-30;
$format=substr($format,3);
$hjMonth = array("محرم", "صفر", "ربيع أول", "ربيع ثاني",
"جماد أول", "جماد ثاني", "رجب", "شعبان", "رمضان", "شوال", "ذو القعدة", "ذو الحجة");
$format=str_replace('j', $d, $format);
$format=str_replace('d', str_pad($d,2,0,STR_PAD_LEFT), $format);
$format=str_replace('l', $arDay[$dayname], $format);
$format=str_replace('F', $hjMonth[$m-1], $format);
$format=str_replace('m', str_pad($m,2,0,STR_PAD_LEFT), $format);
$format=str_replace('n', $m, $format);
$format=str_replace('Y', $y, $format);
$format=str_replace('y', substr($y,2), $format);
$format=str_replace('a', substr($ampm[$am],0,1), $format);
$format=str_replace('A', $ampm[$am], $format);
} elseif ($type=='ar:') {
$format=substr($format,3);
$arMonth=array("Jan"=>"يناير", "Feb"=>"فبراير","Mar"=>"مارس", "Apr"=>"ابريل", "May"=>"مايو",
"Jun"=>"يونيو", "Jul"=>"يوليو", "Aug"=>"اغسطس", "Sep"=>"سبتمبر", "Oct"=>"اكتوبر",
"Nov"=>"نوفمبر", "Dec"=>"ديسمبر");
$format=str_replace('l', $arDay[$dayname], $format);
$format=str_replace('F', $arMonth[$monthname], $format);
$format=str_replace('a', substr($ampm[$am],0,1), $format);
$format=str_replace('A', $ampm[$am], $format);
}
$date = date($format, $timestamp);
if ($use_span) return '<span dir="rtl" lang="ar-sa">'.$date.'</span>';
else return $date;
}
function ard_int($float) {
return ($float < -0.0000001) ? ceil($float-0.0000001) : floor($float+0.0000001);
}
eric at nitrateNO_SPAM dot nl
08-Dec-2002 08:16
Here is a quick example of how to iterate through all days
between 2 dates (with a adjustable increment)
---------------------------------------------------------
//make time stamps from our start & end dates
$start_time = mktime(0,0,0,$start_month,$start_day,$start_year);
$end_time = mktime(0,0,0,$end_month,$end_day,$end_year);
//find the number of days between start_time & end_time
$days = ($end_time - $start_time) / (24 * 3600);
//we want to count the days including the first ..
$days++;
//select a 1 week interval ..
$inc=7;
//find all days (actually periods since we use a increment)
for ($i=0;$i<$days;$i+=$inc)
{
//calculate start & end of period using some magic of mktime :)
$start_date = date("Y-m-d", mktime(0,0,0,$start_month,$start_day+$i,$start_year));
$end_date = date("Y-m-d", mktime(0,0,0,$start_month,$start_day+$i+$inc-1,$start_year));
//print it all ...
print("Period start:" . $start_date . "\n");
print("Period end: " . $end_date . "\n");
}
asg at ftpproxy dot org
24-Sep-2002 04:23
If you like to have the last day of the current month, try this oneliner:
$lastday = strftime ("%d.%m.%Y", (mktime (0,0,0,(date(m)+1),0,(date(Y)))));
-
nightowl at NOS-PA-M dot uk2 dot net
30-Jul-2002 01:59
I wanted to find all records in my database which match the current week (for a call-back function). I made up this function to find the start and end of the current week :
function week($curtime) {
$date_array = getdate (time());
$numdays = $date_array["wday"];
$startdate = date("Y-m-d", time() - ($numdays * 24*60*60));
$enddate = date("Y-m-d", time() + ((7 - $numdays) * 24*60*60));
$week['start'] = $startdate;
$week['end'] = $enddate;
return $week;
}
mwedgwood at ILUVSPAMhotmail dot com
31-Mar-2002 04:24
In vincentv's examples, you should use gmmktime instead of mktime for portability across time zones. For example:
function DateSub($timestamp, $unit, $amount) {
// Possible $units are: "hr", "min", "sec",
// "mon", "day", or "yr"
// $amount should be an integer
$delta_vars = array("hr"=>0, "min"=>0,
"sec"=>0, "mon"=>1,
"day"=>1,"yr"=>1970);
$delta_vars[$unit] += $amount;
$delta = gmmktime($delta_vars["hr"],
$delta_vars["min"],
$delta_vars["sec"],
$delta_vars["mon"],
$delta_vars["day"],
$delta_vars["yr"]);
return $timestamp - $delta;
}
mindaugas at roventa dot lt
18-Feb-2002 06:31
Some lines about LeapYear and day count of month:
function mod($a,$b)
{
$x1=(int) abs($a/$b);
$x2=$a/$b;
return $a-($x1*$b);
}
function IsLeapYear($dt)
{
$y=$dt["year"];
$bulis=((mod($y,4)==0) && ((mod ($y,100)<>0) || (mod($y,400)==0)));
return $bulis;
}
function daycount($dt)
{
$dc_year=$dt["year"];
$dc_month=$dt["mon"];
$dc_day=$dt["mday"];
switch ($dc_month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
break;
case 4:
case 6:
case 9:
case 11:
return 30;
break;
case 2:
if (IsLeapYear($dt)) { return 28; } else { return 29; };
break;
}
}
php-contrib at i-ps dot nospam dot net
30-Jan-2002 09:07
Someone may find this info of some use:
Rules for calculating a leap year:
1) If the year divides by 4, it is a leap year (1988, 1992, 1996 are leap years)
2) Unless it divides by 100, in which case it isn't (1900 divides by 4, but was not a leap year)
3) Unless it divides by 400, in which case it is actually a leap year afterall (So 2000 was a leap year).
In practical terms, to work out the number of days in X years, multiply X by 365.2425, rounding DOWN to the last whole number, should give you the number of days.
The result will never be more than one whole day inaccurate, as opposed to multiplying by 365, which, over more years, will create a larger and larger deficit.
vincentv at thevoid dot demon dot nl
07-Feb-2001 08:23
Some general date functions.
function sub($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
$mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
return $timestamp - $mytime;
}
function add($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
$mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
return $timestamp + $mytime;
}
function dayOfWeek($timestamp) {
return intval(strftime("%w",$timestamp));
}
function daysInMonth($timestamp) {
$timepieces = getdate($timestamp);
$thisYear = $timepieces["year"];
$thisMonth = $timepieces["mon"];
for($thisDay=1;checkdate($thisMonth,$thisDay,$thisYear);$thisDay++);
return $thisDay;
}
function firstDayOfMonth($timestamp) {
$timepieces = getdate($timestamp);
return mktime( $timepieces["hours"],
$timepieces["minutes"],
$timepieces["seconds"],
$timepieces["mon"],
1,
$timepieces["year"]);
}
function monthStartWeekDay($timestamp) {
return dayOfWeek(firstDayOfMonth($timestamp));
}
function weekDayString($weekday) {
$myArray = Array( 0 => "Sun",
1 => "Mon",
2 => "Tue",
3 => "Wed",
4 => "Thu",
5 => "Fri",
6 => "Sat");
return $myArray[$weekday];
}
function stripTime($timestamp) {
$timepieces = getdate($timestamp);
return mktime( 0,
0,
0,
$timepieces["mon"],
$timepieces["mday"],
$timepieces["year"]);
}
function getDayOfYear($timestamp) {
$timepieces = getdate($timestamp);
return intval($timepieces["yday"]);
}
function getYear($timestamp) {
$timepieces = getdate($timestamp);
return intval($timepieces["year"]);
}
function dayDiff($timestamp1,$timestamp2) {
$dayInYear1 = getDayOfYear($timestamp1);
$dayInYear2 = getDayOfYear($timestamp2);
return ((getYear($dayInYear1)*365 + $dayInYear1) -
(getYear($dayInYear2)*365 + $dayInYear2));
}
hope they are usefull to you.
- Vincent
th at definitynet dot com
11-Jan-2001 02:00
I had some problems with dates between mySQL and PHP. PHP had all these great date functions but I wanted to store a usable value in my database tables. In this case I was using TIMESTAMP(14) <or 'YYYYMMDDHHMMSS'>.
This is perhaps the easiest way I have found to pull the PHP usable UNIX Datestamp from my mySQL datestamp stored in the tables:
Use the mySQL UNIX_TIMESTAMP() function in your SQL definition string. i.e.
$sql= "SELECT field1, field2, UNIX_TIMESTAMP(field3) as your_date
FROM your_table
WHERE field1 = '$value'";
The query will return a temp table with coulms "field1" "Field2" "your_date"
The "your_date" will be formatted in a UNIX TIMESTAMP! Now you can use the PHP date() function to spew out nice date formats.
Sample using above $sql:
20010111002747 = Date Stored on mySQL table (TIMESTAMP(14))
979172867 = value returned as your_date in sql stmt (UNIX_TIMESTAMP)
if we use $newdate = date("F jS, Y -- g:ia", $row["your_date"]);
--(after fetching our array from the sql results of course)--
echo "$newdate"; --Will produce:
January 11th, 2001 -- 12:27am
Hope this helps someone out there!
joey dot garcia at usa dot net
13-Nov-2000 03:13
I was trying to make a Month-At-A-Glance and I finally got it to work so I thought I'd share it too. What you need to get this to work is the "Day Of The Week Number", i.e., Sunday=1 and the "Number Of Days in the Month". I also used Allan Kent's Date/Time Column at PHPBuilder to get the required information. I also added the process I used to the requried information.
Enjoy!
<html>
<head>
<title>Month-At-A-Glance</title>
</head>
<body>
<?php
print "<table width=80% align=center border=1>\n";
print"<tr><th>Sun(1)</th> <th>Mon(2)</th> <th>Tue(3)</th> <th>Wed(4)</th> <th>Thu(5)</th> <th>Fri(6)</th> <th>Sat(7)</th> </tr>";
$daysinmonth=31;$daycount=1;
$firstdayofmonth=7;for ($week=1; $week <= 6; $week++){
print"<tr>\n";
for($day=1; $day <=7; $day++){
if( ($day >= $firstdayofmonth) || ($week >1) ){
print"<td height=40px>";
if ($daycount <= $daysinmonth){
print $daycount;
$daycount++;
}
print" </td>\n";
}
else{
print"<td height=40px> </td>\n";
}
}
print"\n</tr>\n";
}
print"</table>";
?>
</body>
</html>
teddk at box100 dot com
08-Sep-2000 06:02
24-Apr-2000 09:44
Regarding the postings regarding MySQL timestamps, please be aware that there are several MySQL date and time types, as documented at
http://www.mysql.com/Manual_chapter/manual_Reference.html#Date_and_time_types
So, in reference to the above posts, nic_lee's algorhythm works on the MySQL TIMESTAMP type, while jmat's function works on the MySQL DATETIME type -- they are NOT the same!
| |