Actually in regards to sagar's week functionality, there's a much better way. Well, to at least get the start_timestamp. I'm sure y'all can figure out the end_timestamp on your own. This is part of a script I wrote some time back and uses $_GET['year'] and $_GET['week'] if the user was moving around the calendar. Otherwise it loaded the current week.
Some might ask about January 4th, but according to the official ISO specification or something, January 4th is always in week 1, so it works out.
Oh... and it doesn't work with daylight savings time as well but since it starts on a Monday, for the most part, it won't affect really anything.
<?php
// Get today
$date = time();
// Get times (minute, hour, day) in seconds
$ms = 1 * 60;
$hs = 1 * 60 * $ms;
$ds = 1 * 24 * $hs;
// Get first day in the week
if ( is_numeric($_GET['year']) && is_numeric($_GET['week']) )
{
$first = strtotime('January 4 '.$_GET['year'].' + '.($_GET['week'] - 1).' weeks');
$first = $first - $ds * ( date('w', $first) - 1 );
}
else
$first = $date - ( $ds * ( date('w', $date) - 1 ) + $hs * date('H', $date) + $ms * date('i', $date) + date('s', $date) );
?>
날짜와 시간 함수
소개
이 함수들은 PHP가 실행되고 있는 서버로부터 날짜와 시간을 얻을 수 있게 합니다. 여러가지 다른 방법으로 날짜와 시간 출력을 형식화할 수 있습니다.
Note: 이 함수들은 서버의 지역설정에 의존한다는 점을 명심하십시오. 특히 윤년과 일광 절약 시간을 생각해서 작업하십시오. (즉, $date += 7*24*60*60이 아니라 $date = strtotime('+7 days'), $date)을 사용하십시오)
Note: 이 섹션에서 참고하는 타임존은 List of Supported Timezones에서 볼 수 있습니다.
요구 조건
이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.
설치
이 함수들은 설치하지 않아도 사용할 수 있습니다; PHP 코어의 일부입니다.
Note: 최신 버전의 타임존 데이터베이스는 PECL » timezonedb를 통해 설치할 수 있습니다. 윈도우 사용자는 PECL4Win 사이트에서 컴파일 된 DLL을 받을 수 있습니다: » php_timezonedb.dll
실행시 설정
이 함수의 작동은 php.ini 설정에 영향을 받습니다.
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| date.default_latitude | "31.7667" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.default_longitude | "35.2333" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.sunrise_zenith | "90.583333" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.sunset_zenith | "90.583333" | PHP_INI_ALL | Available since PHP 5.0.0. |
| date.timezone | "" | PHP_INI_ALL | Available since PHP 5.1.0. |
위 설정 지시어에 대한 간단한 설명입니다.
- date.default_latitude float
-
The default latitude.
- date.default_longitude float
-
The default longitude.
- date.sunrise_zenith float
-
The default sunrise zenith.
- date.sunset_zenith float
-
The default sunset zenith.
- date.timezone string
-
The default timezone used by all date/time functions if the TZ environment variable isn't set. The precedence order is described in the date_default_timezone_get() page. See List of Supported Timezones for a list of supported timezones.
Note: The first four configuration options are currently only used by date_sunrise() and date_sunset().
자원형
이 확장은 리소스형을 정의하지 않습니다.
예약 상수
The following constants are defined since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).
- DATE_ATOM (string)
- Atom (example: 2005-08-15T15:52:01+00:00)
- DATE_COOKIE (string)
- HTTP Cookies (example: Monday, 15-Aug-05 15:52:01 UTC)
- DATE_ISO8601 (string)
- ISO-8601 (example: 2005-08-15T15:52:01+0000)
- DATE_RFC822 (string)
- RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
- DATE_RFC850 (string)
- RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
- DATE_RFC1036 (string)
- RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
- DATE_RFC1123 (string)
- RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
- DATE_RFC2822 (string)
- RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)
- DATE_RFC3339 (string)
- Same as DATE_ATOM (since PHP 5.1.3)
- DATE_RSS (string)
- RSS (Mon, 15 Aug 2005 15:52:01 +0000)
- DATE_W3C (string)
- World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)
Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().
Table of Contents
- checkdate — 그레고리안력 날짜를 확인합니다.
- date_create — Returns new DateTime object
- date_date_set — Sets the date
- date_default_timezone_get — Gets the default timezone used by all date/time functions in a script
- date_default_timezone_set — Sets the default timezone used by all date/time functions in a script
- date_format — Returns date formatted according to given format
- date_isodate_set — Sets the ISO date
- date_modify — Alters the timestamp
- date_offset_get — Returns the daylight saving time offset
- date_parse — Returns associative array with detailed info about given date
- date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
- 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_time_set — Sets the time
- date_timezone_get — Return time zone relative to given DateTime
- date_timezone_set — Sets the time zone for the DateTime object
- date — 로컬 날짜/시간을 형식화합니다.
- getdate — 날짜/시간 정보를 가져온다
- 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
- timezone_abbreviations_list — Returns associative array containing dst, offset and the timezone name
- timezone_identifiers_list — Returns numerically index array with all timezone identifiers
- timezone_name_from_abbr — Returns the timezone name from abbrevation
- timezone_name_get — Returns the name of the timezone
- timezone_offset_get — Returns the timezone offset from GMT
- timezone_open — Returns new DateTimeZone object
- timezone_transitions_get — Returns all transitions for the timezone
날짜/시간
05-Aug-2008 11:59
19-Mar-2008 08:47
With PHP 5.1 and 5.2 the languages datetime support has changed. Although these functions should guess your local timezone settings, they may fail if using a default configuration in a "pre-5.1 way", which means setting no timezone for PHP. In the case PHP could not get a timezone it emits a E_STRICT warning. Note that this affects _all_ datetime functions and keep it in mind when porting software from previous versions to 5.1 or later! It may also confuse your error handling (this is the way I noticed that things have changed, since these changes are not documentated _here_).
References:
http://www.php.net/manual/de/migration51.datetime.php
http://www.php.net/manual/de/migration52.datetime.php
29-Feb-2008 01:53
<?php
####################################
# Provide week number and get start_timestamp and end_timestamp
#####################################
// this week number will come from the timeshare form
$week = 51;
$times = get_start_and_end_date_from_week($week);
$start_time = $times['start_timestamp'];
$end_time = $times['end_timestamp'];
function get_start_and_end_date_from_week ($w)
{
$y = date("Y", time());
$o = 6; // week starts from sunday by default
$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"]));
$sday = $calcdate["mday"];
$smonth = $calcdate["mon"];
$syear = $calcdate["year"];
$timestamp['start_timestamp'] = mktime(0, 0, 0, $smonth, $sday, $syear);
$timestamp['end_timestamp'] = $timestamp['start_timestamp'] + (60*60*24*7);
return $timestamp;
} # function datefromweek
?>
05-Feb-2008 09:56
Here's my version of date diff that handles leap years, DST, and deals with the diff in terms of "human calculations". For example, this code does not assume that a year = 365.25 days, or that a month = 30/31 days. The results are exactly what a human being would determine as a good result.
<?php
/**
* this code assumes php >= 5.1.0. if using < 5.1, read
* php.net/strtotime and change the condition for checking
* for failure from strtotime()
*/
// $t1, $t2: unix times, or strtotime parseable
// $precision: max number of units to output
// $abbr: if true, use "hr" instead of "hour", etc.
function date_diff ($t1, $t2, $precision = 6, $abbr = false) {
if (preg_match('/\D/', $t1) && ($t1 = strtotime($t1)) === false)
return false;
if (preg_match('/\D/', $t2) && ($t2 = strtotime($t2)) === false)
return false;
if ($t1 > $t2)
list($t1, $t2) = array($t2, $t1);
$diffs = array(
'year' => 0, 'month' => 0, 'day' => 0,
'hour' => 0, 'minute' => 0, 'second' => 0,
);
$abbrs = array(
'year' => 'yr', 'month' => 'mth', 'day' => 'day',
'hour' => 'hr', 'minute' => 'min', 'second' => 'sec'
);
foreach (array_keys($diffs) as $interval) {
while ($t2 >= ($t3 = strtotime("+1 ${interval}", $t1))) {
$t1 = $t3;
++$diffs[$interval];
}
}
$stack = array();
foreach ($diffs as $interval => $num)
$stack[] = array($num, ($abbr ? $abbrs[$interval] : $interval) . ($num != 1 ? 's' : ''));
$ret = array();
while (count($ret) < $precision && ($item = array_shift($stack)) !== null) {
if ($item[0] > 0)
$ret[] = "{$item[0]} {$item[1]}";
}
return implode(', ', $ret);
}
$t1 = 'Feb 4, 2008 12:16:00';
$t2 = 'Jul 3, 2006 16:15:30';
echo date_diff($t1, $t2), "\n",
date_diff($t1, $t2, 3), "\n",
date_diff($t1, $t2, 2, true), "\n";
?>
06-Nov-2007 08:14
A better and accurate function to calculate the difference between 2 dates. Takes leap years and DST into consideration. Accepts string date or timestamp as arguments.
<?php
function date_diff($d1, $d2){
$d1 = (is_string($d1) ? strtotime($d1) : $d1);
$d2 = (is_string($d2) ? strtotime($d2) : $d2);
$diff_secs = abs($d1 - $d2);
$base_year = min(date("Y", $d1), date("Y", $d2));
$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
return array(
"years" => date("Y", $diff) - $base_year,
"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
"months" => date("n", $diff) - 1,
"days_total" => floor($diff_secs / (3600 * 24)),
"days" => date("j", $diff) - 1,
"hours_total" => floor($diff_secs / 3600),
"hours" => date("G", $diff),
"minutes_total" => floor($diff_secs / 60),
"minutes" => (int) date("i", $diff),
"seconds_total" => $diff_secs,
"seconds" => (int) date("s", $diff)
);
}
$a = date_diff("2006-11-01", "2007-11-01");
echo "<pre>";
print_r($a);
echo "</pre>";
?>
This example will output (if your timezone uses US DST):
Array
(
[years] => 0
[months_total] => 11
[months] => 11
[days_total] => 364
[days] => 30
[hours_total] => 8759
[hours] => 23
[minutes_total] => 525540
[minutes] => 0
[seconds_total] => 31532400
[seconds] => 0
)
As you can see, the result is not exactly 1 year (less 1 hour) since Nov 1, 2006 is not DST while Nov 1, 2007 is DST.
26-Oct-2007 07:33
May be useful for somebody. This function takes on daylight saving time
<?php
Function DateDiff($date1,$date2) {
$timedifference=$date2-$date1;
$corr=date("I",$date2)-date("I",$date1);
$timedifference+=$corr;
return $timedifference;
}
?>
Example:
<?php
$d1=mktime(2,0,0,10,28,2007);
$d2=mktime(4,0,0,10,28,2007);
$period=DateDiff($d1,$d2);
printf("<br>%s",date("I d.m.Y H:i",$d1));
printf("<br>%u hour",$period/3600);
printf("<br>%s",date("I d.m.Y H:i",$d2));
?>
Getting 2 hour instead 3.
18-Oct-2007 04:42
Not really elegant, but tells you, if your installed timezonedb is the most recent:
<?php
class TestDateTimeTimezonedbVersion extends PHPUnit_Framework_TestCase
{
public function testTimezonedbIsMostRecent()
{
ini_set( 'date.timezone', 'Europe/Berlin' );
ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_contents();
ob_end_clean();
$start = strpos( $info, 'Timezone Database Version' ) + 29;
$this->assertTrue( FALSE !== $start, 'Seems there is no timezone DB installed' );
$end = strpos( $info, "\n", $start );
$installedVersion = substr( $info, $start, $end - $start );
exec( 'pecl remote-info timezonedb', &$output );
$availableVersion = substr( $output[2], 12 );
$this->assertEquals( $availableVersion, $installedVersion,
'The installed timezonedb is not actual. Installed: '.$installedVersion
.' available: '.$availableVersion
);
}
}
?>
12-Oct-2007 05:44
Updating internal's PHP timezone database (5.1.x and 5.2.x)
http://fischer.tecnologia.ws/en/node/1
[editor: Although this does work, it's often easier just to install the pecl timezonedb extension - they should be up-to-date with the latest possible information]
25-Sep-2007 05:25
I wrote a simple script to format a duration in seconds. Give the function some value in seconds and it will return an array.
<?php
function format_duration($seconds) {
$periods = array(
'centuries' => 3155692600,
'decades' => 315569260,
'years' => 31556926,
'months' => 2629743,
'weeks' => 604800,
'days' => 86400,
'hours' => 3600,
'minutes' => 60,
'seconds' => 1
);
$durations = array();
foreach ($periods as $period => $seconds_in_period) {
if ($seconds >= $seconds_in_period) {
$durations[$period] = floor($seconds / $seconds_in_period);
$seconds -= $durations[$period] * $seconds_in_period;
}
}
return $durations;
}
echo format_duration(864);
/*
[minutes] => 14
[seconds] => 24
*/
echo format_duration(3600);
/*
[hours] => 1
*/
echo format_duration(11111111);
/*
[months] => 4
[days] => 6
[hours] => 20
[minutes] => 28
[seconds] => 59
*/
?>
07-Sep-2007 12:54
I was looking for a solution where I could return the number of days, hours, Minutes and seconds between two entries in a table.
DATE_DIFF is not running on my mysql server as my provider uses mysql version 4.0.25
Solution was to use to days and std time functions to calculate the difference in one call.
The fields stored in the table(report_table) are
time(00:00:00),
date(0000-00-00) and record(enum) which tells the app the type of log stored. EG start or end of a report.
SELECT
(TO_DAYS( `end`.`date` ) - TO_DAYS( `start`.`date` ))
-
( second( `end`.`time` ) + (minute( `end`.`time` )*60) + (hour( `end`.`time` )*3600)
<
second( `start`.`time` ) + (minute( `start`.`time` )*60) + (hour( `start`.`time` )*3600))
AS `days` ,
SEC_TO_TIME(
(second( `end`.`time` ) + (minute( `end`.`time` )*60) + (hour( `end`.`time` )*3600) )
-
(second( `start`.`time` ) + (minute( `start`.`time` )*60) + (hour( `start`.`time` )*3600) )
) AS `hms`,
`start`.`time` as `start`,
`end`.`time` as `end`
FROM `report_table` AS `start` , `report_table` AS `end`
AND `start`.`record` = 'Report Begin'
AND `end`.`record` = 'Report End'
LIMIT 1
If there is no end of report then it will not return a result, as you would expect.
16-Feb-2007 12:50
Here is my function to count the number days, weeks, months, and year. I tried it below 1970 and it works.
<?php
function datecal($date,$return_value)
{
$date = explode("/", $date);
$month_begin = $date[0];
$month_begin_date = $date[1];
$year1 = $date[2];
$month_end = date("n");
$month_end_date = date("j");
$year2 = date("Y");
$days_old = 0;
$years_old = 0;
$months_old = 0;
if($month_begin==12)
{
$month = 1;
$year = $year1+1;
}
else
{
$month = $month_begin+1;
$year = $year1;
}
$begin_plus_days = cal_days_in_month(CAL_GREGORIAN, $month_begin, $year1) - $month_begin_date;
$end_minus_days = cal_days_in_month(CAL_GREGORIAN, $month_end, $year2) - $month_end_date;
while ($year <= $year2)
{
if($year == $year2)
{
$days_old = $days_old + cal_days_in_month(CAL_GREGORIAN, $month, $year);
if($month < $month_end)
{
$months_old = $months_old + 1;
$month = $month + 1;
}
elseif ($month==$month_end and $month_end_date >= $month_begin_date)
{
$year = $year2+1;
}
else
{
$year = $year2+1;
}
}
else
{
$days_old = $days_old + cal_days_in_month(CAL_GREGORIAN, $month, $year);
if ($month <= 11)
{
$month = $month + 1;
$months_old = $months_old + 1;
}
else
{
$month = 1;
$year = $year + 1;
$months_old = $months_old + 1;
}
}
}
$days_old = ($days_old + $begin_plus_days) - $end_minus_days;
if($return_value == "d")
{ return $days_old; }
elseif ($return_value == "w")
{ return intval($days_old/7); }
elseif ($return_value == "m")
{ return $months_old; }
elseif ($return_value == "y")
{ return intval($months_old/12); }
}
echo datecal("08/13/1975","m");
?>
17-Jan-2007 10:08
When debugging code that stores date/time values in a database, you may find yourself wanting to know the date/time that corresponds to a given unix timestamp, or the timestamp for a given date & time.
The following script will do the conversion either way. If you give it a numeric timestamp, it will display the corresponding date and time. If you give it a date and time (in almost any standard format), it will display the timestamp.
All conversions are done for your locale/time zone.
<?php
while (true)
{
// Read a line from standard in.
echo "enter time to convert: ";
$inline = fgets(STDIN);
$inline = trim($inline);
if ($inline == "" || $inline == ".")
break;
// See if the line is a date.
$pos = strpos($inline, "/");
if ($pos === false) {
// not a date, should be an integer.
$date = date("m/d/Y G:i:s", $inline);
echo "int2date: $inline -> $date\n";
} else {
$itime = strtotime($inline);
echo "date2int: $inline -> $itime\n";
}
}
?>
07-Nov-2006 04:27
Another month late on this, but I would amend alex's post to recommend using gmdate() any time you're trying to represent a "delta time", or your local timezone is likely to interfere.
For example, a five minute difference (300 seconds) would appear as follows in New York:
echo date('z:H:i:s', 300);
// 364:19:05:00
echo gmdate('z:H:i:s', 300);
// 0:00:05:00
Thanks for the 'z', though, Alex. Up until now, I've always been dividing that out -- hadn't found it in the format list. :-)
13-Sep-2006 01:50
A few months late on this, but I just saw cepercival at thatMailThatsHot dot com 's post, and think that it may be a bit easier to just use this as opposed to writing it by hand:
date("z:H:i:s", $endTimestamp - $startTimestamp);
Since the timestamps store seconds from the unix epoch, and the unix epoch occured at the very beginning of a year, you can get away with this.
It gets a little trickier to place the years, but it should work fine if you subtract out the number of years date("Y", 0) returns. This would naturally require two seperate calls to the date function- one to find the year, and one to find the rest of the information.
11-Jul-2006 09:31
Hopefully this may be useful to someone out there!
I wanted a simple function to give me a duration for phone calls using a start timestamp and end timestamp. After finding an understandable example here http://www.brenlei.com/articles/php/dates/dates4.php i cobbled this together:
<?php
function callDuration($dateTimeBegin,$dateTimeEnd) {
$dif=$dateTimeEnd - $dateTimeBegin;
$hours = floor($dif / 3600);
$temp_remainder = $dif - ($hours * 3600);
$minutes = floor($temp_remainder / 60);
$temp_remainder = $temp_remainder - ($minutes * 60);
$seconds = $temp_remainder;
// leading zero's - not bothered about hours
$min_lead=':';
if($minutes <=9)
$min_lead .= '0';
$sec_lead=':';
if($seconds <=9)
$sec_lead .= '0';
// difference/duration returned as Hours:Mins:Secs e.g. 01:29:32
return $hours.$min_lead.$minutes.$sec_lead.$seconds;
}
?>
obviously it can be easily extended to include days, weeks etc.
Stupidly simple I know but that's how i like it.
28-Sep-2005 09:08
<?php
//function like dateDiff Microsoft
//not error in year Bissesto
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
}
}
?>
27-Sep-2005 04:46
Calculate Sum BusinessDays (Mon till Fri) between two date's :
<?php
function businessdays($begin, $end) {
$rbegin = is_string($begin) ? strtotime(strval($begin)) : $begin;
$rend = is_string($end) ? strtotime(strval($end)) : $end;
if ($rbegin < 0 || $rend < 0)
return 0;
$begin = workday($rbegin, TRUE);
$end = workday($rend, FALSE);
if ($end < $begin) {
$end = $begin;
$begin = $end;
}
$difftime = $end - $begin;
$diffdays = floor($difftime / (24 * 60 * 60)) + 1;
if ($diffdays < 7) {
$abegin = getdate($rbegin);
$aend = getdate($rend);
if ($diffdays == 1 && ($astart['wday'] == 0 || $astart['wday'] == 6) && ($aend['wday'] == 0 || $aend['wday'] == 6))
return 0;
$abegin = getdate($begin);
$aend = getdate($end);
$weekends = ($aend['wday'] < $abegin['wday']) ? 1 : 0;
} else
$weekends = floor($diffdays / 7);
return $diffdays - ($weekends * 2);
}
function workday($date, $begindate = TRUE) {
$adate = getdate($date);
$day = 24 * 60 * 60;
if ($adate['wday'] == 0) // Sunday
$date += $begindate ? $day : -($day * 2);
elseif ($adate['wday'] == 6) // Saterday
$date += $begindate ? $day * 2 : -$day;
return $date;
}
?>
09-Jun-2005 03:49
This dateDiff() function can take in just about any timestamp, including UNIX timestamps and anything that is accepted by strtotime(). It returns an array with the ability to split the result a couple different ways. I built this function to suffice any datediff needs I had. Hope it helps others too.
<?php
/********* dateDiff() function **********
* returns Array of Int values for difference between two dates
* $date1 > $date2 --> positive integers are returned
* $date1 < $date2 --> negative integers are returned
*
* $split recognizes the following:
* 'yw' = splits up years, weeks and days (default)
* 'y' = splits up years and days
* 'w' = splits up weeks and days
* 'd' = total days
*
* examples:
* $dif1 = dateDiff() or dateDiff('yw')
* $dif2 = dateDiff('y')
* $dif3 = dateDiff('w')
* $dif4 = dateDiff('d')
*
* assuming dateDiff returned 853 days, the above
* examples would have a print_r output of:
* $dif1 == Array( [y] => 2 [w] => 17 [d] => 4 )
* $dif2 == Array( [y] => 2 [d] => 123 )
* $dif3 == Array( [w] => 121 [d] => 6 )
* $dif4 == Array( [d] => 847 )
*
* note: [h] (hours), [m] (minutes), [s] (seconds) are always returned as elements of the Array
*/
function dateDiff($dt1, $dt2, $split='yw') {
$date1 = (strtotime($dt1) != -1) ? strtotime($dt1) : $dt1;
$date2 = (strtotime($dt2) != -1) ? strtotime($dt2) : $dt2;
$dtDiff = $date1 - $date2;
$totalDays = intval($dtDiff/(24*60*60));
$totalSecs = $dtDiff-($totalDays*24*60*60);
$dif['h'] = $h = intval($totalSecs/(60*60));
$dif['m'] = $m = intval(($totalSecs-($h*60*60))/60);
$dif['s'] = $totalSecs-($h*60*60)-($m*60);
// set up array as necessary
switch($split) {
case 'yw': # split years-weeks-days
$dif['y'] = $y = intval($totalDays/365);
$dif['w'] = $w = intval(($totalDays-($y*365))/7);
$dif['d'] = $totalDays-($y*365)-($w*7);
break;
case 'y': # split years-days
$dif['y'] = $y = intval($totalDays/365);
$dif['d'] = $totalDays-($y*365);
break;
case 'w': # split weeks-days
$dif['w'] = $w = intval($totalDays/7);
$dif['d'] = $totalDays-($w*7);
break;
case 'd': # don't split -- total days
$dif['d'] = $totalDays;
break;
default:
die("Error in dateDiff(). Unrecognized \$split parameter. Valid values are 'yw', 'y', 'w', 'd'. Default is 'yw'.");
}
return $dif;
}
?>
07-Jun-2005 05:55
For those who are using pre MYSQL 4.1.1, you can use:
TO_DAYS([Date Value 1])-TO_DAYS([Date Value 2])
For the same result as:
DATEDIFF([Date Value 1],[Date Value 2])
11-Oct-2004 05:43
Before you get too advanced using date functions, be sure also to see the calendar functions at http://www.php.net/manual/en/ref.calendar.php .
13-Apr-2004 05: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 inc