I have written a little Date Class Library for PHP that supports timestamps for dates greater than 2038 and lesser than 1970.
This library can be used in both PHP4 and PHP5.
Check it out here:
http://xwisdomhtml.com/dateclass.html
date
(PHP 4, PHP 5)
date — Formatuje lokalny czas/datę
Opis
Zwraca datę sformatowaną według szablonu podanego w argumencie format . Żądana data określona jest w argumencie znacznik_czasu , a w przypadku jego braku pobierany jest aktualny czas.
Informacja: Poprawny zakres znacznika czasu to zwykle od piątku, 13 grudnia 1901 20:45:54 GMT (czasu Greenwich) do wtorku, 19 stycznia 2038 03:14:07 GMT. (Wartości te odpowiadają minimalnej i maksymalnej wartości 32-bitowej liczbie całkowitej ze znakiem). W systemie Windows zakres ten jest bardziej ograniczony i zawiera się w przedziale 01-01-1970 do 19-01-2038.
Wygenerowanie znacznika czasu z daty zapisanej jako łańcuch znaków umożliwia funkcja strtotime(). Również niektóre systemy baz danych mają funkcje konwersji ich formatów daty w uniksowy znacznik czasu (jak np. funkcja UNIX_TIMESTAMP w MySQL-u).
Poniższych znaków używa się w szablonie formatującym datę:
- a - "am" lub "pm"
- A - "AM" lub "PM"
- B - Czas internetowy Swatcha
- d - dzień miesiąca, 2 cyfry z zerem na początku; tzn. od "01" do "31"
- D - dzień tygodnia, tekst, 3 litery; n.p. "Fri"
- F - miesiąc, tekst, pełna nazwa; n.p. "January"
- g - godzina, format 12-godzinny bez zera na początku; tzn. od "1" do "12"
- G - godzina, format 24-godzinny bez zera na początku; tzn. od "0" do "23"
- h - godzina, format 12-godzinny z zerem na początku; tzn. od "01" do "12"
- H - godzina, format 24-godzinny z zerem na początku; tzn. od "00" do "23"
- i - minuty; tzn. od "00" do "59"
- I (duża litera i) - "1" jeśli czas oszczędzania światła słonecznego (w Polsce - czas letni), "0" jeśli czas standardowy (w Polsce - zimowy)
- j - dzień miesiąca bez zera na początku; tzn. od "1" do "31"
- l (mała litera 'L') - dzień tygodnia, tekst, pełna nazwa; n.p. "Friday"
- L - "1" jeśli rok przestępny, "0" w przeciwnym razie
- m - miesiąc; tzn. "01" to "12"
- M - miesiąc, tekst, 3 litery; n.p. "Jan"
- n - miesiąc bez zera na początku; tzn. "1" to "12"
- O - różnica w stosunku do czasu Greenwich; n.p. "+0200"
- r - data sformatowana według RFC 822; n.p. "Thu, 21 Dec 2000 16:01:07 +0200" (dodane w PHP 4.0.4)
- s - sekundy; i.e. "00" to "59"
- S - standardowy angielski sufiks liczebnika porządkowego, 2 litery; tzn. "st", "nd", "rd" lub "th"
- t - liczba dni w danym miesiącu; tzn. od "28" do "31"
- T - strefa czasowa ustawiona na tej maszynie; n.p. "EST" lub "MDT"
- U - liczba sekund od uniksowej Epoki (1 stycznia 1970 00:00:00 GMT)
- w - dzień tygodnia, liczbowy, tzn. od "0" (Niedziela) do "6" (Sobota)
- W - numer tygodnia w roku według ISO-8601, tydzień zaczyna się w poniedziałek (dodane w PHP 4.1.0)
- Y - rok, 4 liczby; n.p. "1999"
- y - rok, 2 liczby; n.p. "99"
- z - dzień roku; tzn. od "0" do "365"
- Z - ofset strefy czasowej w sekundach (tzn. pomiędzy "-43200" a "43200"). Ofset dla stref czasowych na zachód od UTC (południka zero) jest zawsze ujemny a dla tych na wschód od UTC jest zawsze dodatni.
Example #1 przykłady użycia date()
echo date ("l dS of F Y h:i:s A");
echo "July 1, 2000 is on a " . date ("l", mktime(0,0,0,7,1,2000));
Jeśli nie chcesz, aby któryś z rozpoznawalnych w szablonie znaków został zastąpiony odpowiadającą mu częścią daty, musisz poprzedzić go znakiem odwrotnego ukośnika (backslash). Jeśli znak razem z odwrotnym ukośnikiem tworzy jakiś znak specjalny, musisz również zacytować ukośnik odwrotny.
Example #2 Opuszczanie znaków w szablonie date()
echo date("l \\t\h\e jS"); // wyświetla tekst typu 'Saturday the 8th'
Można użyć date() i mktime() razem, aby odszukać daty w przyszłości lub przeszłości.
Example #3 przykłady zastosowania date() i mktime()
$jutro = mktime (0,0,0,date("m") ,date("d")+1,date("Y"));
$ostatni_miesiac = mktime (0,0,0,date("m")-1,date("d"), date("Y"));
$kolejny_rok = mktime (0,0,0,date("m"), date("d"), date("Y")+1);
Informacja: Rozwiązanie to jest bardziej godne zaufania od dodawania lub odejmowania określonej liczby sekund, chociażby z powodu zmiany czasu.
Poniżej znajduje się kilka przykładów zastosowania date(). Proszę zwrócić uwagę, że powinno się cytować wszystkie znaki aby uniknąć nieoczekiwanych rezultatów, a poza tym, nawet te znaki, które obecnie nie mają znaczenia, mogą mieć przypisane jakieś znaczenie w przyszłych wersjach PHP. O ile to możliwe, należy używać cudzysłowów pojedynczych, żeby uniknąć np. zamiany \n na znak nowej linii.
Example #4 zastosowania date()
/* Dzisiaj jest 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
Aby sformatować datę w innych językach, należy użyć funkcji setlocale() i strftime().
Patrz także getlastmod(), gmdate(), mktime(), strftime() i time().
date
26-Mar-2008 04:44
21-Mar-2008 10:29
Find out how many days a month has (including leap-years) in one single line command:
$numberOfDays = date("d", mktime(0, 0, 0, $month + 1, 0, $year));
This is possible because if you set the field "day" as ZERO in MKTIME, it will consider the last day of month-1.
20-Mar-2008 05:26
in regards to: [takzik at ebanat dot com]
simplest way of displaying / formatting dates. strtotime()
<?php
# Date: y-m-d => d-m-y
$time =explode("-","2008-01-01");
krsort($time);
print implode("-",$time);
?>
<p>Will return: 01-01-2008.
<?php
# Date: d-m-y => y-m-d
$time =explode("-","01-01-2008");
krsort($time);
print "<p>".implode("-",$time);
?>
<p>Will return: 2008-01-01.
<?php
# Quickest: Y-m-d => American Format
print date("m-d-Y",strtotime("2008-02-01"));
?>
<p>Will return: 02-01-2008.
<?php
# Quickest: Y-m-d => Brittish Format
print date("d.m.Y",strtotime("2008-01-01"));
?>
<p>Will return: 01.01.2008.
17-Mar-2008 06:56
Useful tool for creating DATE() specs without having to run 35 tests to get it right: http://www.bitbybit.dk/mysql/date_format/ (says mysql, but covers PHP as well)
17-Mar-2008 05:09
Here is an easy MySQL way of getting the difference in dates. For me it is more logical to do this on the select than running it though an additional PHP function after selecting the date. But depends on what your doing of course. I hope it helps.
SELECT ABS(DATEDIFF(NOW(),yourdateField)) as dateDiff
29-Feb-2008 10:05
## This will produce the first day of last month and the last day of last month
## 2008-01-01 2008-01-31
<?php
echo date("Y-m-01", strtotime("-1 month", strtotime(date("Y-m-d"))))." ".date("Y-m-d", strtotime("-1 day", strtotime(date("Y-m-01")))) ?>
21-Feb-2008 11:06
The PHP4 replacement for ISO8601 posted by fokeyjoe has a little flaw:
The time in ISO is in 24 hour format, so an uppercase H must be used.
Correct format is:
$sISO8601=date('Y-m-d\TH:i:s',$nTimestamp). substr_replace(date('O',$nTimestamp),':',3,0);
Short version for NOW:
$sISO8601=date('Y-m-d\TH:i:s'). substr_replace(date('O'),':',3,0);
25-Jan-2008 08:59
Complementing the information by ZZigc on 28-Dec-2007 07:38, if you want to calculate the number of weeks in a given year, according to the week definition by ISO 8601, the following should be enough:
date('W', mktime(0,0,0,12,28,$year) );
(the last week on a give year always contains 28-Dec)
31-Dec-2007 03:28
date("W") returns the iso8601 week number, while date("Y") returns the _current_ year. This can lead to odd results. For example today (dec 31, 2007) it returns 1 for the week and of course 2007 for the year. This is not wrong in a strict sense because iso defines this week as the first of 2008 while we still have 2007.
So, if you don't have another way to safely retrieve the year according to the iso8061 week-date - strftime("%G") doesn't work on some systems -, you should be careful when working with date("W").
For most cases strftime("%W") should be a safe replacement.
[edit: Much easier is to use "o" (lower case O) instead of "Y"]
28-Dec-2007 07:38
I wanted to get the number of weeks for particular year.
Example with date():
<?php
$weeks_in_year = date("W", strtotime("12/31/2007"));
?>
It works for years smaller than current year, but returns '01' when year was the same or bigger as current year.
Not sure if I missed something or maybe misused this function but I couldn't get it to work even with different date representations.
So the workaround was using different function.
Example with strftime():
<?php
$weeks_in_year = strftime("%W",strtotime("12/31/2007"));
?>
Now it works as a charm.
PHP v.4.4.7
19-Dec-2007 03:54
re: marius at svr dot ro
to anyone using marius' function, it needs some minor fixes (look for a ---->)
<?php
//The function returns the no. of business days between two dates and it skeeps the holidays
function getWorkingDays($startDate,$endDate,$holidays){
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N",strtotime($startDate));
$the_last_day_of_week = date("N",strtotime($endDate));
//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week <= $the_last_day_of_week){
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else{
if ($the_first_day_of_week <= 6) $no_remaining_days--;
//In the case when the interval falls in two weeks, there will be a Sunday for sure
$no_remaining_days--;
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
$workingDays += $no_remaining_days;
}
//We subtract the holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn't fall in weekend
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays--;
}
return $workingDays;
}
//Example:
$holidays=array("2006-12-25","2006-12-26","2007-01-01");
echo getWorkingDays("2006-12-22","2007-01-06",$holidays)
// => will return 8
?>
Otherwise, I found this very useful, thanks marius:)
14-Dec-2007 01:56
For JasonLFunk
I did some testing on the occurrence for a given date within the month (i.e 1st Monday, 2nd Wednesday, 3rd Friday, etc.).
where $dDate is a getdate() array
intval(($dDate['mday']-1)/7)+1
Returns an integer representing the week for a given date. I tested on a complete calendar month and it seems to work well.
I then convert to a string and compare to a string list of values to see if it is in the list. If it is - it qualifies. So, my list of values might be '2,4' representing every 2nd and 4th occurrence.
12-Dec-2007 04:44
This function is like date, but it "speaks" Hungarian (or an other language)
<?php
/*
these are the hungarian additional format characters
ö: full textual representation of the day of the week
Ö: full textual representation of the day of the week (first character is uppercase),
ő: short textual representation of the day of the week,
Ő: short textual representation of the day of the week (first character is uppercase),
ü: full textual representation of a month
Ü: full textual representation of a month (first character is uppercase),
ű: short textual representation of a month
Ű: short textual representation of a month (first character is uppercase),
*/
function date_hu($formatum, $timestamp=0) {
if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
$q['ö'] = array(-1 => 'w', 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat');
$q['Ö'] = array(-1 => 'w', 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat');
$q['ő'] = array(-1 => 'w', 'va', 'hé', 'ke', 'sze', 'csü', 'pé', 'szo');
$q['Ő'] = array(-1 => 'w', 'Va', 'Hé', 'Ke', 'Sze', 'Csü', 'Pé', 'Szo');
$q['ü'] = array(-1 => 'n', '', 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december');
$q['Ü'] = array(-1 => 'n', '', 'Január', 'Február', 'Március', 'Április', 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December');
$q['ű'] = array(-1 => 'n', '', 'jan', 'febr', 'márc', 'ápr', 'máj', 'júni', 'júli', 'aug', 'szept', 'okt', 'nov', 'dec');
$q['Ű'] = array(-1 => 'n', '', 'Jan', 'Febr', 'Márc', 'Ápr', 'Máj', 'Júni', 'Júli', 'Aug', 'Szept', 'Okt', 'Nov', 'Dec');
if ($timestamp == 0)
$timestamp = time();
$temp = '';
$i = 0;
while ( (strpos($formatum, 'ö', $i) !== FALSE) || (strpos($formatum, 'Ö', $i) !== FALSE) ||
(strpos($formatum, 'ő', $i) !== FALSE) || (strpos($formatum, 'Ő', $i) !== FALSE) ||
(strpos($formatum, 'ü', $i) !== FALSE) || (strpos($formatum, 'Ü', $i) !== FALSE) ||
(strpos($formatum, 'ű', $i) !== FALSE) || (strpos($formatum, 'Ű', $i) !== FALSE)) {
$ch['ö']=strpos($formatum, 'ö', $i);
$ch['Ö']=strpos($formatum, 'Ö', $i);
$ch['ő']=strpos($formatum, 'ő', $i);
$ch['Ő']=strpos($formatum, 'Ő', $i);
$ch['ü']=strpos($formatum, 'ü', $i);
$ch['Ü']=strpos($formatum, 'Ü', $i);
$ch['ű']=strpos($formatum, 'ű', $i);
$ch['Ű']=strpos($formatum, 'Ű', $i);
foreach ($ch as $k=>$v)
if ($v === FALSE)
unset($ch[$k]);
$a = min($ch);
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
$i = $a+1;
}
$temp .= date(substr($formatum, $i), $timestamp);
return $temp;
}
echo date_hu('Y. ü j. (ö) G:i');
?>
20-Nov-2007 02:24
For those of us who don't have 5.x installed (that puts a colon in the time zone)...
<?php
$timezone = date("O"); // get timezone
$timezone_end = substr($timezone, -2, 2); // get last two numbers
$timezone= substr($timezone, 0, -2); // get first half
echo $timezone = $timezone . ":" . $timezone_end; // add colon
?>
30-Oct-2007 03:30
Hello, these notes have been very helpful and help me solve the following problem.
I have a db with scheduled items that contain a start date, a day to occur on and how many weeks from the next closest day to happen again. I wrote the following script to do the following
1. Accept : starting date, the current date, the number of weeks between occurances and the day of the week it is to occur on.
2. Find the closest future day of the week argument from the start date.
3. Find out when the next time the item should happen via the weeks inbetween and the closest day of the week to the start date.
The result could be compared with your current date to trigger your periodical item or simply to find out when the next occurances will happen.
// $startDate:Date
// $todayDate:Date
// $weeks:Int - number of weeks in between
// $wantDay:String - full day of the week
function getWeekPeriodDate($startDate,$todayDate,$weeks,$wantDay){
$startDate = date("Y-m-d", strtotime("next $wantDay" ,strtotime($startDate)));
$dayDiff = round((strtotime($startDate)-strtotime($todayDate))/(24*60*60),0);
$weekPeriodDiff = abs(round($dayDiff/7/$weeks)*$weeks);
return date("Y-m-d",strtotime($startDate . " + " . $weekPeriodDiff . " weeks"));
}
Usage :getWeekPeriodDate("2006-July-1","2007-Nov-5",8,"Tuesday")
returns : 2007-11-20 (which is the next Tuesday based on 8 week periods since the next Tuesday closest to the start date)
30-Aug-2007 06:06
I modified (erenezgu at gmail.com)'s code so you don't have to redirect but is stored in cookies.
<?php
if(empty($_COOKIE['offset'])) {
// Javascript is our friend!
$header='
<script type="text/javascript">
document.cookie="offset=" + ( (new Date()).getTimezoneOffset()*60)*(-1)-'.abs(date('Z')).';
</script>
';
}
// Example Usage
echo date('d/m/Y H:i:s', time()+$_COOKIE['offset'] );
?>
10-Aug-2007 09:39
If there is an easier way to find the week of the month, let me know. Here is how I figured out how to do it;
date("W") - date("W",strtotime(date("F") . " 1st " . date("Y"))) + 1;
20-Jul-2007 08:00
In relation to soreenpk at yahoo dot com's message:
That code doesn't work for two dates with a difference larger than a year, for example:
$digest_date = "2006-04-14";
$date2="2007-04-15";
$date_diff = date("d",strtotime($date2)) - date("d",strtotime($digest_date));//$date_diff = 1
16-Jul-2007 04:18
Here is a backward compatible version of dates_interconv
http://www.php.net/manual/en/function.date.php#71397
which also works with time (hours, minutes and seconds) and months in "M" format (three letters):
<?php
/**
mod of
http://www.php.net/manual/en/function.date.php#71397
* Converts a date and time string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
*
* @param string $date_format1
* @param string $date_format2
* @param string $date_str
* @return string
*/
function dates_interconv($date_format1, $date_format2, $date_str)
{
$base_struc = split('[:/.\ \-]', $date_format1);
$date_str_parts = split('[:/.\ \-]', $date_str );
// print_r( $base_struc ); echo "\n"; // for testing
// print_r( $date_str_parts ); echo "\n"; // for testing
$date_elements = array();
$p_keys = array_keys( $base_struc );
foreach ( $p_keys as $p_key )
{
if ( !empty( $date_str_parts[$p_key] ))
{
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
}
else
return false;
}
// print_r($date_elements); // for testing
if (array_key_exists('M', $date_elements)) {
$Mtom=array(
"Jan"=>"01",
"Feb"=>"02",
"Mar"=>"03",
"Apr"=>"04",
"May"=>"05",
"Jun"=>"06",
"Jul"=>"07",
"Aug"=>"08",
"Sep"=>"09",
"Oct"=>"10",
"Nov"=>"11",
"Dec"=>"12",
);
$date_elements['m']=$Mtom[$date_elements['M']];
}
// print_r($date_elements); // for testing
$dummy_ts = mktime(
$date_elements['H'],
$date_elements['i'],
$date_elements['s'],
$date_elements['m'],
$date_elements['d'],
$date_elements['Y']
);
return date( $date_format2, $dummy_ts );
}
?>
Usage:
<?php
$df_src = 'd/m/Y H:i:s';
$df_des = 'Y-m-d H:i:s';
echo dates_interconv( $df_src, $df_des, '25/12/2005 23:59:59');
?>
Output:
2005-12-25 23:59:59
03-Jul-2007 01:11
For people who used "z" format...
The real range of "z" key format is 0 to 365 (instead of 366) and "z" represent the number of spent days in the year.
See this examples :
<?php
define ("\n" , NL );
print '<pre>';
print '"z" format interpretation:' . NL . NL;
print 'On 0 timestamp: "' . date( 'z : Y-m-d' , 0 ) . '"' . NL;
//show: On 0 timestamp: "0 : 1970-01-01"
print 'On second unix day: "' . date( 'z : Y-m-d' , 3600*24 ) . '"' . NL;
//show: On second unix day: "1 : 1970-01-02"
print 'On the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31, 2000 ) ) . '"' . NL;
//show: On the last day of a leap year: "365 : 2000-12-31"
print 'On the day after the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31+1, 2000 ) ) . '"' . NL;
//show: On the day after the last day of a leap year: "0 : 2001-01-01"
print '</pre>';
?>
19-Jun-2007 07:48
i needed the day (eg. 27th) of the last Monday of a month
<?php
$d=cal_days_in_month(CAL_GREGORIAN,$m,$y); // days in month
if (date('l',mktime(0,0,0,$m,$d,$y))=='Monday'): $finalmonday=$d;
else: $finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,$d,$y))); // day(date) of last monday of month, eg 26
endif;
?>
this also works...
<?php
$finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,($d+1),$y)));
//the '$d+1' is to catch the last day IS a monday (eg. dec 2007)
?>
Hope it helps, BigJonMX
14-Jun-2007 05:05
<?php
/**
* Get date in RFC3339
* For example used in XML/Atom
*
* @param integer $timestamp
* @return string date in RFC3339
* @author Boris Korobkov
* @see http://tools.ietf.org/html/rfc3339
*/
function date3339($timestamp=0) {
if (!$timestamp) {
$timestamp = time();
}
$date = date('Y-m-d\TH:i:s', $timestamp);
$matches = array();
if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
$date .= $matches[1].$matches[2].':'.$matches[3];
} else {
$date .= 'Z';
}
return $date;
}
?>
12-Jun-2007 03:55
Just a small addition to dmitriy. If the present date is in daylight saving time, and the date in the past is not, the result will not be a whole number by dividing by 86400. It will be something like 48.958333333. This is because the day in which it changes from normal to daylight saving time is one hour longer than normal (90000 secs) and the opposite is true when changing back (the day would be one hour shorter - 82800 secs).
If you want a whole number of days use the following instead:
<?php
$digest_date = "2007-01-01";
$date_diff = round( abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400, 0 );
?>
11-Jun-2007 05:55
soreenpk - the code snippet you posted will not find the day difference between two days that are not in the same month. This will:
<?php
$digest_date = "2007-06-01";
$date_diff = abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400;
?>
86400 is the number of seconds in a day, so finding the date difference in seconds and converting to days will give true day difference between dates. Cheers.
20-May-2007 09:30
This is an implementation for days360 formula used in financial calc software, this asumes year with 360 days and months with 30 days.
I am looking for a reliable function to add days to a date using 30[E]/360 format.
<?php
/* Calc days between two dates using the financial calendar
30/360 (usa) or 30E/360(european)<-default
$fecha1 and $fecha2 in format: aaaa-mm-dd
return days or -1 in case of error.
based on cost_analysis.py module Ver. 0.1 public domain, no license required by Harm Kirchhoff
*/
function days_360($fecha1,$fecha2,$europeo=true) {
//try switch dates: min to max
if( $fecha1 > $fecha2 ) {
$temf = $fecha1;
$fecha1 = $fecha2;
$fecha2 = $temf;
}
// get day month year...
list($yy1, $mm1, $dd1) = explode('-', $fecha1);
list($yy2, $mm2, $dd2) = explode('-', $fecha2);
if( $dd1==31) { $dd1 = 30; }
//checks according standars: 30E/360 or 30/360.
if(!$europeo) {
if( ($dd1==30) and ($dd2==31) ) {
$dd2=30;
} else {
if( $dd2==31 ) {
$dd2=30;
}
}
}
//check for invalid date
if( ($dd1<1) or ($dd2<1) or ($dd1>30) or ($dd2>31) or
($mm1<1) or ($mm2<1) or ($mm1>12) or ($mm2>12) or
($yy1>$yy2) ) {
return(-1);
}
if( ($yy1==$yy2) and ($mm1>$mm2) ) { return(-1); }
if( ($yy1==$yy2) and ($mm1==$mm2) and ($dd1>$dd2) ) { return(-1); }
//Calc
$yy = $yy2-$yy1;
$mm = $mm2-$mm1;
$dd = $dd2-$dd1;
return( ($yy*360)+($mm*30)+$dd );
}
// usage:
echo days_360("2007-01-13","2007-05-20");
?>
03-May-2007 06:52
Another method for getting close to ISO8601 using PHP4 (should cover all versions). This format gets you compliant RDF/RSS feed dates:
$sISO8601=date('Y-m-d\Th:i:s',$nTimestamp). substr_replace(date('O',$nTimestamp),':',3,0);
The main limitation I'm aware of is the non-compliant year around new year.
24-Apr-2007 09:37
To everyone who is posting functions to parse date strings and turn them into time stamps - please look at the strtotime() function. It probably already does whatever you're writing a function to do.
To the person right below me: while your function might be an extremely small bit more efficient, strtotime() will work just fine.
10-Mar-2007 09:14
Note for wips week limits function:
I had to run it over 52 weeks of the year and it was very slow so I've modified to improve:
function week_limits($weekNumber, $year, $pattern)
{
$pattern = ($pattern) ? $pattern : "m/d";
$stday = 7 * $weekNumber - 7;
$stDayNumber = date("w", mktime(0,0,0,1, 1+$stday, $year));
$stUtime = mktime(0,0,0,1,1+$stday-$stDayNumber, $year);
$start_time = date($pattern, $stUtime);
$end_time = date($pattern, $stUtime+6*24*60*60);
return array($start_time, $end_time);
}//week_limits()
05-Feb-2007 07:54
Re: steve at somejunkwelike dot com
I think this is a better function to find the business days between two dates. This function requires PHP 5.1.0.
<?php
//The function returns the no. of business days between two dates and it skeeps the holidays
function getWorkingDays($startDate,$endDate,$holidays){
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N",strtotime($startDate));
$the_last_day_of_week = date("N",strtotime($endDate));
//The two can't be equal because the $no_remaining_days (the interval between $the_first_day_of_week and $the_last_day_of_week) is at most 6
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week < $the_last_day_of_week){
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else{
if ($the_first_day_of_week <= 6) $no_remaining_days--;
//In the case when the interval falls in two weeks, there will be a Sunday for sure
$no_remaining_days--;
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
$workingDays = $no_full_weeks * 5 + $no_remaining_days;
//We subtract the holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn't fall in weekend
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays--;
}
return $workingDays;
}
//Example:
$holidays=array("2006-12-25","2006-12-26","2007-01-01");
echo getWorkingDays("2006-12-22","2007-01-06",$holidays)
// => will return 8
?>
30-Jan-2007 04:37
Determine what is next month:
I Had the same issue as matt_wbdi at hotmail dot com
Simple solution is use 1 for the day instead of date("d"), it didnt seem to matter if I use "m", or "n" for the month.
// eg:
// if today is 2007-01-30 the following:
$datePlusoneMonth = mktime(0, 0, 0, date("m")+ 1, date("d"), date("Y"));
echo date("Y-m", $datePlusoneMonth);
//returns 2007-03 which is not next month
// this worked for me:
$datePlusoneMonth = mktime(0, 0, 0, date("m")+ 1, 1, date("Y"));
echo date("Y-m", $datePlusoneMonth);
// returns 2007-02, which IS next month
30-Jan-2007 10:06
The below code doesn't work. The $next_month variable, for instance, right now, will be March, even though today is January 30th. The reason is because one month from Jan. 30th is March. But that's not the next month. I would suggest using an array of Month names instead, with their respective number as the key.
17-Jan-2007 10:22
I wanted to shift an sql date forward by a set time period.
This is how I achived it... well handy.
<?
function sql_date_shift($date, $shift)
{
return date("Y-m-d H:i:s" , strtotime($shift, strtotime($date)));
}
// example usage
$date = "2006-12-31 21:00";
$shift "+6 hours"; // could be days, weeks... see function strtotime() for usage
echo sql_date_shift($date, $shift);
// will output: 2007-01-01 03:00:00
?>
Hope it is of use,
Ashley
22-Dec-2006 08:22
In example 3, <?php date("m") ?> is passed to mktime() for the month argument. I believe <?php date("n") ?> should be used instead so that the leading 0's don't make PHP think the arguments are octal values. The same goes for <?php date("j") ?> instead off <?php date("d") ?>.
<?php
echo mktime(0, 0, 0, 09, 09, 2006);
echo "\n";
echo mktime(0, 0, 0, 9, 9, 2006);
?>
1133326800
1157774400
if you are sending your data to a database, you can just send time() and then use strftime() to turn the time() string into readable time format.
check both time() and strftime() functions both offer more or less same functionality as date(). date() can also be used with time() strings to display time in the past.
more or less with something like:
date("j F, Y - g:ia", $data['date_quoted'])
where time() = $data['date_quoted'] and time() is the exact time date when the string is executed. if this is done towards a database, the time() stored is the actual server time upon script execution, no matter the time set in the individual computer, this will record server time, unless a gmt is set in newer versions of php (5 and up).
26-Nov-2006 10:30
/**
* Converts a date string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
*
* @param string $date_format1
* @param string $date_format2
* @param string $date_str
* @return string
*/
function dates_interconv( $date_format1, $date_format2, $date_str )
{
$base_struc = split('[/.-]', $date_format1);
$date_str_parts = split('[/.-]', $date_str );
print_r( $base_struc ); echo "<br>";
print_r( $date_str_parts ); echo "<br>";
$date_elements = array();
$p_keys = array_keys( $base_struc );
foreach ( $p_keys as $p_key )
{
if ( !empty( $date_str_parts[$p_key] ))
{
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
}
else
return false;
}
$dummy_ts = mktime( 0,0,0, $date_elements['m'],$date_elements['d'],$date_elements['Y']);
return date( $date_format2, $dummy_ts );
}
$df_src = 'd/m/Y';
$df_des = 'Y-m-d';
$iso_date = dates_interconv( $df_src, $df_des, '25/12/2005');
output:
2005-12-25
16-Nov-2006 05:56
date("W") will not take into account US-system of weeks (it starts on Sunday).
Example:
According to ISO 8601, 1 Jan 2006 is on Sunday therefore in US-system 1 -- 7 January will be 52 week and not 1st!
But date() will print 1 and not 52.
07-Nov-2006 02:06
So I wanted a little function to output an easy to read but inaccurate date. I came up with the following (probably very inefficient) little function;
<?php
function ezDate($d) {
$ts = time() - strtotime(str_replace("-","/",$d));
if($ts>31536000) $val = round($ts/31536000,0).' year';
else if($ts>2419200) $val = round($ts/2419200,0).' month';
else if($ts>604800) $val = round($ts/604800,0).' week';
else if($ts>86400) $val = round($ts/86400,0).' day';
else if($ts>3600) $val = round($ts/3600,0).' hour';
else if($ts>60) $val = round($ts/60,0).' minute';
else $val = $ts.' second';
if($val>1) $val .= 's';
return $val;
}
?>
Then I use it as follows;
<?php
echo ucwords(ezDate('2006-09-07 18:42:00')).' Ago';
?>
Which would output;
2 Months Ago
I add an acronym tag around the output also, so my users can mouse-over for the exact date.
Hope it helps someone!
26-Oct-2006 10:38
my quick and dirty code to find the season of the current date
<?php
function season() {
$limits=array('/12/21'=>'Winter', '/09/21'=>'Autumn', '/06/21'=>'Summer', '/03/21'=>'Spring', '/01/01'=>'Winter');
foreach ($limits AS $key => $value) {
$limit=date("Y").$key;
if (strtotime($adate)>=strtotime($limit)) {
return $value;
}
}
}
echo season();
?>
PS: the 21th is a good approach but not the real day.
23-Oct-2006 05:13
If you want to use the date function to fix the RFC-822 format from an allready made RSS 2.0 feed you can do it like this..
Maybe getting an external feed from another asp or php file that you cannot change, but want to have the correct dateformat for anyway.
<?php
header('Content-type: application/rss+xml; charset=iso-8859-1');
$xmlfile = simplexml_load_file($_GET[feedURL]);
for ( $i = 0; $i < count($xmlfile->channel->item); $i++ )
$xmlfile->channel->item[$i]->pubDate = date("r",strtotime((string)($xmlfile->channel->item[$i]->pubDate)));
echo $xmlfile->asXML();
?>
Then simply link to your rss feed like this
filename.php?feedURL=