DateObject.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Date
  17. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @version $Id$
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. */
  21. /**
  22. * @category Zend
  23. * @package Zend_Date
  24. * @subpackage Zend_Date_DateObject
  25. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  26. * @license http://framework.zend.com/license/new-bsd New BSD License
  27. */
  28. abstract class Zend_Date_DateObject {
  29. /**
  30. * UNIX Timestamp
  31. */
  32. private $_unixTimestamp;
  33. protected static $_cache = null;
  34. protected static $_defaultOffset = 0;
  35. /**
  36. * active timezone
  37. */
  38. private $_timezone = 'UTC';
  39. private $_offset = 0;
  40. private $_syncronised = 0;
  41. // turn off DST correction if UTC or GMT
  42. protected $_dst = true;
  43. /**
  44. * Table of Monthdays
  45. */
  46. private static $_monthTable = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  47. /**
  48. * Table of Years
  49. */
  50. private static $_yearTable = array(
  51. 1970 => 0, 1960 => -315619200, 1950 => -631152000,
  52. 1940 => -946771200, 1930 => -1262304000, 1920 => -1577923200,
  53. 1910 => -1893456000, 1900 => -2208988800, 1890 => -2524521600,
  54. 1880 => -2840140800, 1870 => -3155673600, 1860 => -3471292800,
  55. 1850 => -3786825600, 1840 => -4102444800, 1830 => -4417977600,
  56. 1820 => -4733596800, 1810 => -5049129600, 1800 => -5364662400,
  57. 1790 => -5680195200, 1780 => -5995814400, 1770 => -6311347200,
  58. 1760 => -6626966400, 1750 => -6942499200, 1740 => -7258118400,
  59. 1730 => -7573651200, 1720 => -7889270400, 1710 => -8204803200,
  60. 1700 => -8520336000, 1690 => -8835868800, 1680 => -9151488000,
  61. 1670 => -9467020800, 1660 => -9782640000, 1650 => -10098172800,
  62. 1640 => -10413792000, 1630 => -10729324800, 1620 => -11044944000,
  63. 1610 => -11360476800, 1600 => -11676096000);
  64. /**
  65. * Set this object to have a new UNIX timestamp.
  66. *
  67. * @param string|integer $timestamp OPTIONAL timestamp; defaults to local time using time()
  68. * @return string|integer old timestamp
  69. * @throws Zend_Date_Exception
  70. */
  71. protected function setUnixTimestamp($timestamp = null)
  72. {
  73. $old = $this->_unixTimestamp;
  74. if (is_numeric($timestamp)) {
  75. $this->_unixTimestamp = $timestamp;
  76. } else if ($timestamp === null) {
  77. $this->_unixTimestamp = time();
  78. } else {
  79. require_once 'Zend/Date/Exception.php';
  80. throw new Zend_Date_Exception('\'' . $timestamp . '\' is not a valid UNIX timestamp', $timestamp);
  81. }
  82. return $old;
  83. }
  84. /**
  85. * Returns this object's UNIX timestamp
  86. * A timestamp greater then the integer range will be returned as string
  87. * This function does not return the timestamp as object. Use copy() instead.
  88. *
  89. * @return integer|string timestamp
  90. */
  91. protected function getUnixTimestamp()
  92. {
  93. if ($this->_unixTimestamp === intval($this->_unixTimestamp)) {
  94. return (int) $this->_unixTimestamp;
  95. } else {
  96. return (string) $this->_unixTimestamp;
  97. }
  98. }
  99. /**
  100. * Internal function.
  101. * Returns time(). This method exists to allow unit tests to work-around methods that might otherwise
  102. * be hard-coded to use time(). For example, this makes it possible to test isYesterday() in Date.php.
  103. *
  104. * @param integer $sync OPTIONAL time syncronisation value
  105. * @return integer timestamp
  106. */
  107. protected function _getTime($sync = null)
  108. {
  109. if ($sync !== null) {
  110. $this->_syncronised = round($sync);
  111. }
  112. return (time() + $this->_syncronised);
  113. }
  114. /**
  115. * Internal mktime function used by Zend_Date.
  116. * The timestamp returned by mktime() can exceed the precision of traditional UNIX timestamps,
  117. * by allowing PHP to auto-convert to using a float value.
  118. *
  119. * Returns a timestamp relative to 1970/01/01 00:00:00 GMT/UTC.
  120. * DST (Summer/Winter) is depriciated since php 5.1.0.
  121. * Year has to be 4 digits otherwise it would be recognised as
  122. * year 70 AD instead of 1970 AD as expected !!
  123. *
  124. * @param integer $hour
  125. * @param integer $minute
  126. * @param integer $second
  127. * @param integer $month
  128. * @param integer $day
  129. * @param integer $year
  130. * @param boolean $gmt OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
  131. * @return integer|float timestamp (number of seconds elapsed relative to 1970/01/01 00:00:00 GMT/UTC)
  132. */
  133. protected function mktime($hour, $minute, $second, $month, $day, $year, $gmt = false)
  134. {
  135. // complete date but in 32bit timestamp - use PHP internal
  136. if ((1901 < $year) and ($year < 2038)) {
  137. $oldzone = @date_default_timezone_get();
  138. // Timezone also includes DST settings, therefor substracting the GMT offset is not enough
  139. // We have to set the correct timezone to get the right value
  140. if (($this->_timezone != $oldzone) and ($gmt === false)) {
  141. date_default_timezone_set($this->_timezone);
  142. }
  143. $result = ($gmt) ? @gmmktime($hour, $minute, $second, $month, $day, $year)
  144. : @mktime($hour, $minute, $second, $month, $day, $year);
  145. date_default_timezone_set($oldzone);
  146. return $result;
  147. }
  148. if ($gmt !== true) {
  149. $second += $this->_offset;
  150. }
  151. if (isset(self::$_cache)) {
  152. $id = strtr('Zend_DateObject_mkTime_' . $this->_offset . '_' . $year.$month.$day.'_'.$hour.$minute.$second . '_'.(int)$gmt, '-','_');
  153. if ($result = self::$_cache->load($id)) {
  154. return unserialize($result);
  155. }
  156. }
  157. // date to integer
  158. $day = intval($day);
  159. $month = intval($month);
  160. $year = intval($year);
  161. // correct months > 12 and months < 1
  162. if ($month > 12) {
  163. $overlap = floor($month / 12);
  164. $year += $overlap;
  165. $month -= $overlap * 12;
  166. } else {
  167. $overlap = ceil((1 - $month) / 12);
  168. $year -= $overlap;
  169. $month += $overlap * 12;
  170. }
  171. $date = 0;
  172. if ($year >= 1970) {
  173. // Date is after UNIX epoch
  174. // go through leapyears
  175. // add months from latest given year
  176. for ($count = 1970; $count <= $year; $count++) {
  177. $leapyear = self::isYearLeapYear($count);
  178. if ($count < $year) {
  179. $date += 365;
  180. if ($leapyear === true) {
  181. $date++;
  182. }
  183. } else {
  184. for ($mcount = 0; $mcount < ($month - 1); $mcount++) {
  185. $date += self::$_monthTable[$mcount];
  186. if (($leapyear === true) and ($mcount == 1)) {
  187. $date++;
  188. }
  189. }
  190. }
  191. }
  192. $date += $day - 1;
  193. $date = (($date * 86400) + ($hour * 3600) + ($minute * 60) + $second);
  194. } else {
  195. // Date is before UNIX epoch
  196. // go through leapyears
  197. // add months from latest given year
  198. for ($count = 1969; $count >= $year; $count--) {
  199. $leapyear = self::isYearLeapYear($count);
  200. if ($count > $year)
  201. {
  202. $date += 365;
  203. if ($leapyear === true)
  204. $date++;
  205. } else {
  206. for ($mcount = 11; $mcount > ($month - 1); $mcount--) {
  207. $date += self::$_monthTable[$mcount];
  208. if (($leapyear === true) and ($mcount == 1)) {
  209. $date++;
  210. }
  211. }
  212. }
  213. }
  214. $date += (self::$_monthTable[$month - 1] - $day);
  215. $date = -(($date * 86400) + (86400 - (($hour * 3600) + ($minute * 60) + $second)));
  216. // gregorian correction for 5.Oct.1582
  217. if ($date < -12220185600) {
  218. $date += 864000;
  219. } else if ($date < -12219321600) {
  220. $date = -12219321600;
  221. }
  222. }
  223. if (isset(self::$_cache)) {
  224. self::$_cache->save( serialize($date), $id);
  225. }
  226. return $date;
  227. }
  228. /**
  229. * Returns true, if given $year is a leap year.
  230. *
  231. * @param integer $year
  232. * @return boolean true, if year is leap year
  233. */
  234. protected static function isYearLeapYear($year)
  235. {
  236. // all leapyears can be divided through 4
  237. if (($year % 4) != 0) {
  238. return false;
  239. }
  240. // all leapyears can be divided through 400
  241. if ($year % 400 == 0) {
  242. return true;
  243. } else if (($year > 1582) and ($year % 100 == 0)) {
  244. return false;
  245. }
  246. return true;
  247. }
  248. /**
  249. * Internal mktime function used by Zend_Date for handling 64bit timestamps.
  250. *
  251. * Returns a formatted date for a given timestamp.
  252. *
  253. * @param string $format format for output
  254. * @param mixed $timestamp
  255. * @param boolean $gmt OPTIONAL true = other arguments are for UTC time, false = arguments are for local time/date
  256. * @return string
  257. */
  258. protected function date($format, $timestamp = null, $gmt = false)
  259. {
  260. $oldzone = @date_default_timezone_get();
  261. if ($this->_timezone != $oldzone) {
  262. date_default_timezone_set($this->_timezone);
  263. }
  264. if ($timestamp === null) {
  265. $result = ($gmt) ? @gmdate($format) : @date($format);
  266. date_default_timezone_set($oldzone);
  267. return $result;
  268. }
  269. if (abs($timestamp) <= 0x7FFFFFFF) {
  270. $result = ($gmt) ? @gmdate($format, $timestamp) : @date($format, $timestamp);
  271. date_default_timezone_set($oldzone);
  272. return $result;
  273. }
  274. $jump = false;
  275. $origstamp = $timestamp;
  276. if (isset(self::$_cache)) {
  277. $idstamp = strtr('Zend_DateObject_date_' . $this->_offset . '_'. $timestamp . '_'.(int)$gmt, '-','_');
  278. if ($result2 = self::$_cache->load($idstamp)) {
  279. $timestamp = unserialize($result2);
  280. $jump = true;
  281. }
  282. }
  283. // check on false or null alone failes
  284. if (empty($gmt) and empty($jump)) {
  285. $tempstamp = $timestamp;
  286. if ($tempstamp > 0) {
  287. while (abs($tempstamp) > 0x7FFFFFFF) {
  288. $tempstamp -= (86400 * 23376);
  289. }
  290. $dst = date("I", $tempstamp);
  291. if ($dst === 1) {
  292. $timestamp += 3600;
  293. }
  294. $temp = date('Z', $tempstamp);
  295. $timestamp += $temp;
  296. }
  297. if (isset(self::$_cache)) {
  298. self::$_cache->save( serialize($timestamp), $idstamp);
  299. }
  300. }
  301. if (($timestamp < 0) and ($gmt !== true)) {
  302. $timestamp -= $this->_offset;
  303. }
  304. date_default_timezone_set($oldzone);
  305. $date = $this->getDateParts($timestamp, true);
  306. $length = strlen($format);
  307. $output = '';
  308. for ($i = 0; $i < $length; $i++) {
  309. switch($format[$i]) {
  310. // day formats
  311. case 'd': // day of month, 2 digits, with leading zero, 01 - 31
  312. $output .= (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']);
  313. break;
  314. case 'D': // day of week, 3 letters, Mon - Sun
  315. $output .= date('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
  316. break;
  317. case 'j': // day of month, without leading zero, 1 - 31
  318. $output .= $date['mday'];
  319. break;
  320. case 'l': // day of week, full string name, Sunday - Saturday
  321. $output .= date('l', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday'])));
  322. break;
  323. case 'N': // ISO 8601 numeric day of week, 1 - 7
  324. $day = self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
  325. if ($day == 0) {
  326. $day = 7;
  327. }
  328. $output .= $day;
  329. break;
  330. case 'S': // english suffix for day of month, st nd rd th
  331. if (($date['mday'] % 10) == 1) {
  332. $output .= 'st';
  333. } else if ((($date['mday'] % 10) == 2) and ($date['mday'] != 12)) {
  334. $output .= 'nd';
  335. } else if (($date['mday'] % 10) == 3) {
  336. $output .= 'rd';
  337. } else {
  338. $output .= 'th';
  339. }
  340. break;
  341. case 'w': // numeric day of week, 0 - 6
  342. $output .= self::dayOfWeek($date['year'], $date['mon'], $date['mday']);
  343. break;
  344. case 'z': // day of year, 0 - 365
  345. $output .= $date['yday'];
  346. break;
  347. // week formats
  348. case 'W': // ISO 8601, week number of year
  349. $output .= $this->weekNumber($date['year'], $date['mon'], $date['mday']);
  350. break;
  351. // month formats
  352. case 'F': // string month name, january - december
  353. $output .= date('F', mktime(0, 0, 0, $date['mon'], 2, 1971));
  354. break;
  355. case 'm': // number of month, with leading zeros, 01 - 12
  356. $output .= (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']);
  357. break;
  358. case 'M': // 3 letter month name, Jan - Dec
  359. $output .= date('M',mktime(0, 0, 0, $date['mon'], 2, 1971));
  360. break;
  361. case 'n': // number of month, without leading zeros, 1 - 12
  362. $output .= $date['mon'];
  363. break;
  364. case 't': // number of day in month
  365. $output .= self::$_monthTable[$date['mon'] - 1];
  366. break;
  367. // year formats
  368. case 'L': // is leap year ?
  369. $output .= (self::isYearLeapYear($date['year'])) ? '1' : '0';
  370. break;
  371. case 'o': // ISO 8601 year number
  372. $week = $this->weekNumber($date['year'], $date['mon'], $date['mday']);
  373. if (($week > 50) and ($date['mon'] == 1)) {
  374. $output .= ($date['year'] - 1);
  375. } else {
  376. $output .= $date['year'];
  377. }
  378. break;
  379. case 'Y': // year number, 4 digits
  380. $output .= $date['year'];
  381. break;
  382. case 'y': // year number, 2 digits
  383. $output .= substr($date['year'], strlen($date['year']) - 2, 2);
  384. break;
  385. // time formats
  386. case 'a': // lower case am/pm
  387. $output .= (($date['hours'] >= 12) ? 'pm' : 'am');
  388. break;
  389. case 'A': // upper case am/pm
  390. $output .= (($date['hours'] >= 12) ? 'PM' : 'AM');
  391. break;
  392. case 'B': // swatch internet time
  393. $dayseconds = ($date['hours'] * 3600) + ($date['minutes'] * 60) + $date['seconds'];
  394. if ($gmt === true) {
  395. $dayseconds += 3600;
  396. }
  397. $output .= (int) (($dayseconds % 86400) / 86.4);
  398. break;
  399. case 'g': // hours without leading zeros, 12h format
  400. if ($date['hours'] > 12) {
  401. $hour = $date['hours'] - 12;
  402. } else {
  403. if ($date['hours'] == 0) {
  404. $hour = '12';
  405. } else {
  406. $hour = $date['hours'];
  407. }
  408. }
  409. $output .= $hour;
  410. break;
  411. case 'G': // hours without leading zeros, 24h format
  412. $output .= $date['hours'];
  413. break;
  414. case 'h': // hours with leading zeros, 12h format
  415. if ($date['hours'] > 12) {
  416. $hour = $date['hours'] - 12;
  417. } else {
  418. if ($date['hours'] == 0) {
  419. $hour = '12';
  420. } else {
  421. $hour = $date['hours'];
  422. }
  423. }
  424. $output .= (($hour < 10) ? '0'.$hour : $hour);
  425. break;
  426. case 'H': // hours with leading zeros, 24h format
  427. $output .= (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']);
  428. break;
  429. case 'i': // minutes with leading zeros
  430. $output .= (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']);
  431. break;
  432. case 's': // seconds with leading zeros
  433. $output .= (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']);
  434. break;
  435. // timezone formats
  436. case 'e': // timezone identifier
  437. if ($gmt === true) {
  438. $output .= gmdate('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
  439. $date['mon'], $date['mday'], 2000));
  440. } else {
  441. $output .= date('e', mktime($date['hours'], $date['minutes'], $date['seconds'],
  442. $date['mon'], $date['mday'], 2000));
  443. }
  444. break;
  445. case 'I': // daylight saving time or not
  446. if ($gmt === true) {
  447. $output .= gmdate('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
  448. $date['mon'], $date['mday'], 2000));
  449. } else {
  450. $output .= date('I', mktime($date['hours'], $date['minutes'], $date['seconds'],
  451. $date['mon'], $date['mday'], 2000));
  452. }
  453. break;
  454. case 'O': // difference to GMT in hours
  455. $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset();
  456. $output .= sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
  457. break;
  458. case 'P': // difference to GMT with colon
  459. $gmtstr = ($gmt === true) ? 0 : $this->getGmtOffset();
  460. $gmtstr = sprintf('%s%04d', ($gmtstr <= 0) ? '+' : '-', abs($gmtstr) / 36);
  461. $output = $output . substr($gmtstr, 0, 3) . ':' . substr($gmtstr, 3);
  462. break;
  463. case 'T': // timezone settings
  464. if ($gmt === true) {
  465. $output .= gmdate('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
  466. $date['mon'], $date['mday'], 2000));
  467. } else {
  468. $output .= date('T', mktime($date['hours'], $date['minutes'], $date['seconds'],
  469. $date['mon'], $date['mday'], 2000));
  470. }
  471. break;
  472. case 'Z': // timezone offset in seconds
  473. $output .= ($gmt === true) ? 0 : -$this->getGmtOffset();
  474. break;
  475. // complete time formats
  476. case 'c': // ISO 8601 date format
  477. $difference = $this->getGmtOffset();
  478. $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
  479. $difference = substr($difference, 0, 3) . ':' . substr($difference, 3);
  480. $output .= $date['year'] . '-'
  481. . (($date['mon'] < 10) ? '0' . $date['mon'] : $date['mon']) . '-'
  482. . (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']) . 'T'
  483. . (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']) . ':'
  484. . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
  485. . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds'])
  486. . $difference;
  487. break;
  488. case 'r': // RFC 2822 date format
  489. $difference = $this->getGmtOffset();
  490. $difference = sprintf('%s%04d', ($difference <= 0) ? '+' : '-', abs($difference) / 36);
  491. $output .= gmdate('D', 86400 * (3 + self::dayOfWeek($date['year'], $date['mon'], $date['mday']))) . ', '
  492. . (($date['mday'] < 10) ? '0' . $date['mday'] : $date['mday']) . ' '
  493. . date('M', mktime(0, 0, 0, $date['mon'], 2, 1971)) . ' '
  494. . $date['year'] . ' '
  495. . (($date['hours'] < 10) ? '0' . $date['hours'] : $date['hours']) . ':'
  496. . (($date['minutes'] < 10) ? '0' . $date['minutes'] : $date['minutes']) . ':'
  497. . (($date['seconds'] < 10) ? '0' . $date['seconds'] : $date['seconds']) . ' '
  498. . $difference;
  499. break;
  500. case 'U': // Unix timestamp
  501. $output .= $origstamp;
  502. break;
  503. // special formats
  504. case "\\": // next letter to print with no format
  505. $i++;
  506. if ($i < $length) {
  507. $output .= $format[$i];
  508. }
  509. break;
  510. default: // letter is no format so add it direct
  511. $output .= $format[$i];
  512. break;
  513. }
  514. }
  515. return (string) $output;
  516. }
  517. /**
  518. * Returns the day of week for a Gregorian calendar date.
  519. * 0 = sunday, 6 = saturday
  520. *
  521. * @param integer $year
  522. * @param integer $month
  523. * @param integer $day
  524. * @return integer dayOfWeek
  525. */
  526. protected static function dayOfWeek($year, $month, $day)
  527. {
  528. if ((1901 < $year) and ($year < 2038)) {
  529. return (int) date('w', mktime(0, 0, 0, $month, $day, $year));
  530. }
  531. // gregorian correction
  532. $correction = 0;
  533. if (($year < 1582) or (($year == 1582) and (($month < 10) or (($month == 10) && ($day < 15))))) {
  534. $correction = 3;
  535. }
  536. if ($month > 2) {
  537. $month -= 2;
  538. } else {
  539. $month += 10;
  540. $year--;
  541. }
  542. $day = floor((13 * $month - 1) / 5) + $day + ($year % 100) + floor(($year % 100) / 4);
  543. $day += floor(($year / 100) / 4) - 2 * floor($year / 100) + 77 + $correction;
  544. return (int) ($day - 7 * floor($day / 7));
  545. }
  546. /**
  547. * Internal getDateParts function for handling 64bit timestamps, similar to:
  548. * http://www.php.net/getdate
  549. *
  550. * Returns an array of date parts for $timestamp, relative to 1970/01/01 00:00:00 GMT/UTC.
  551. *
  552. * $fast specifies ALL date parts should be returned (slower)
  553. * Default is false, and excludes $dayofweek, weekday, month and timestamp from parts returned.
  554. *
  555. * @param mixed $timestamp
  556. * @param boolean $fast OPTIONAL defaults to fast (false), resulting in fewer date parts
  557. * @return array
  558. */
  559. protected function getDateParts($timestamp = null, $fast = null)
  560. {
  561. // actual timestamp
  562. if (!is_numeric($timestamp)) {
  563. return getdate();
  564. }
  565. // 32bit timestamp
  566. if (abs($timestamp) <= 0x7FFFFFFF) {
  567. return @getdate((int) $timestamp);
  568. }
  569. if (isset(self::$_cache)) {
  570. $id = strtr('Zend_DateObject_getDateParts_' . $timestamp.'_'.(int)$fast, '-','_');
  571. if ($result = self::$_cache->load($id)) {
  572. return unserialize($result);
  573. }
  574. }
  575. $otimestamp = $timestamp;
  576. $numday = 0;
  577. $month = 0;
  578. // gregorian correction
  579. if ($timestamp < -12219321600) {
  580. $timestamp -= 864000;
  581. }
  582. // timestamp lower 0
  583. if ($timestamp < 0) {
  584. $sec = 0;
  585. $act = 1970;
  586. // iterate through 10 years table, increasing speed
  587. foreach(self::$_yearTable as $year => $seconds) {
  588. if ($timestamp >= $seconds) {
  589. $i = $act;
  590. break;
  591. }
  592. $sec = $seconds;
  593. $act = $year;
  594. }
  595. $timestamp -= $sec;
  596. if (!isset($i)) {
  597. $i = $act;
  598. }
  599. // iterate the max last 10 years
  600. do {
  601. --$i;
  602. $day = $timestamp;
  603. $timestamp += 31536000;
  604. $leapyear = self::isYearLeapYear($i);
  605. if ($leapyear === true) {
  606. $timestamp += 86400;
  607. }
  608. if ($timestamp >= 0) {
  609. $year = $i;
  610. break;
  611. }
  612. } while ($timestamp < 0);
  613. $secondsPerYear = 86400 * ($leapyear ? 366 : 365) + $day;
  614. $timestamp = $day;
  615. // iterate through months
  616. for ($i = 12; --$i >= 0;) {
  617. $day = $timestamp;
  618. $timestamp += self::$_monthTable[$i] * 86400;
  619. if (($leapyear === true) and ($i == 1)) {
  620. $timestamp += 86400;
  621. }
  622. if ($timestamp >= 0) {
  623. $month = $i;
  624. $numday = self::$_monthTable[$i];
  625. if (($leapyear === true) and ($i == 1)) {
  626. ++$numday;
  627. }
  628. break;
  629. }
  630. }
  631. $timestamp = $day;
  632. $numberdays = $numday + ceil(($timestamp + 1) / 86400);
  633. $timestamp += ($numday - $numberdays + 1) * 86400;
  634. $hours = floor($timestamp / 3600);
  635. } else {
  636. // iterate through years
  637. for ($i = 1970;;$i++) {
  638. $day = $timestamp;
  639. $timestamp -= 31536000;
  640. $leapyear = self::isYearLeapYear($i);
  641. if ($leapyear === true) {
  642. $timestamp -= 86400;
  643. }
  644. if ($timestamp < 0) {
  645. $year = $i;
  646. break;
  647. }
  648. }
  649. $secondsPerYear = $day;
  650. $timestamp = $day;
  651. // iterate through months
  652. for ($i = 0; $i <= 11; $i++) {
  653. $day = $timestamp;
  654. $timestamp -= self::$_monthTable[$i] * 86400;
  655. if (($leapyear === true) and ($i == 1)) {
  656. $timestamp -= 86400;
  657. }
  658. if ($timestamp < 0) {
  659. $month = $i;
  660. $numday = self::$_monthTable[$i];
  661. if (($leapyear === true) and ($i == 1)) {
  662. ++$numday;
  663. }
  664. break;
  665. }
  666. }
  667. $timestamp = $day;
  668. $numberdays = ceil(($timestamp + 1) / 86400);
  669. $timestamp = $timestamp - ($numberdays - 1) * 86400;
  670. $hours = floor($timestamp / 3600);
  671. }
  672. $timestamp -= $hours * 3600;
  673. $month += 1;
  674. $minutes = floor($timestamp / 60);
  675. $seconds = $timestamp - $minutes * 60;
  676. if ($fast === true) {
  677. $array = array(
  678. 'seconds' => $seconds,
  679. 'minutes' => $minutes,
  680. 'hours' => $hours,
  681. 'mday' => $numberdays,
  682. 'mon' => $month,
  683. 'year' => $year,
  684. 'yday' => floor($secondsPerYear / 86400),
  685. );
  686. } else {
  687. $dayofweek = self::dayOfWeek($year, $month, $numberdays);
  688. $array = array(
  689. 'seconds' => $seconds,
  690. 'minutes' => $minutes,
  691. 'hours' => $hours,
  692. 'mday' => $numberdays,
  693. 'wday' => $dayofweek,
  694. 'mon' => $month,
  695. 'year' => $year,
  696. 'yday' => floor($secondsPerYear / 86400),
  697. 'weekday' => gmdate('l', 86400 * (3 + $dayofweek)),
  698. 'month' => gmdate('F', mktime(0, 0, 0, $month, 1, 1971)),
  699. 0 => $otimestamp
  700. );
  701. }
  702. if (isset(self::$_cache)) {
  703. self::$_cache->save( serialize($array), $id);
  704. }
  705. return $array;
  706. }
  707. /**
  708. * Internal getWeekNumber function for handling 64bit timestamps
  709. *
  710. * Returns the ISO 8601 week number of a given date
  711. *
  712. * @param integer $year
  713. * @param integer $month
  714. * @param integer $day
  715. * @return integer
  716. */
  717. protected function weekNumber($year, $month, $day)
  718. {
  719. if ((1901 < $year) and ($year < 2038)) {
  720. return (int) date('W', mktime(0, 0, 0, $month, $day, $year));
  721. }
  722. $dayofweek = self::dayOfWeek($year, $month, $day);
  723. $firstday = self::dayOfWeek($year, 1, 1);
  724. if (($month == 1) and (($firstday < 1) or ($firstday > 4)) and ($day < 4)) {
  725. $firstday = self::dayOfWeek($year - 1, 1, 1);
  726. $month = 12;
  727. $day = 31;
  728. } else if (($month == 12) and ((self::dayOfWeek($year + 1, 1, 1) < 5) and
  729. (self::dayOfWeek($year + 1, 1, 1) > 0))) {
  730. return 1;
  731. }
  732. return intval (((self::dayOfWeek($year, 1, 1) < 5) and (self::dayOfWeek($year, 1, 1) > 0)) +
  733. 4 * ($month - 1) + (2 * ($month - 1) + ($day - 1) + $firstday - $dayofweek + 6) * 36 / 256);
  734. }
  735. /**
  736. * Internal _range function
  737. * Sets the value $a to be in the range of [0, $b]
  738. *
  739. * @param float $a - value to correct
  740. * @param float $b - maximum range to set
  741. */
  742. private function _range($a, $b) {
  743. while ($a < 0) {
  744. $a += $b;
  745. }
  746. while ($a >= $b) {
  747. $a -= $b;
  748. }
  749. return $a;
  750. }
  751. /**
  752. * Calculates the sunrise or sunset based on a location
  753. *
  754. * @param array $location Location for calculation MUST include 'latitude', 'longitude', 'horizon'
  755. * @param bool $horizon true: sunrise; false: sunset
  756. * @return mixed - false: midnight sun, integer:
  757. */
  758. protected function calcSun($location, $horizon, $rise = false)
  759. {
  760. // timestamp within 32bit
  761. if (abs($this->_unixTimestamp) <= 0x7FFFFFFF) {
  762. if ($rise === false) {
  763. return date_sunset($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
  764. $location['longitude'], 90 + $horizon, $this->getGmtOffset() / 3600);
  765. }
  766. return date_sunrise($this->_unixTimestamp, SUNFUNCS_RET_TIMESTAMP, $location['latitude'],
  767. $location['longitude'], 90 + $horizon, $this->getGmtOffset() / 3600);
  768. }
  769. // self calculation - timestamp bigger than 32bit
  770. // fix circle values
  771. $quarterCircle = 0.5 * M_PI;
  772. $halfCircle = M_PI;
  773. $threeQuarterCircle = 1.5 * M_PI;
  774. $fullCircle = 2 * M_PI;
  775. // radiant conversion for coordinates
  776. $radLatitude = $location['latitude'] * $halfCircle / 180;
  777. $radLongitude = $location['longitude'] * $halfCircle / 180;
  778. // get solar coordinates
  779. $tmpRise = $rise ? $quarterCircle : $threeQuarterCircle;
  780. $radDay = $this->date('z',$this->_unixTimestamp) + ($tmpRise - $radLongitude) / $fullCircle;
  781. // solar anomoly and longitude
  782. $solAnomoly = $radDay * 0.017202 - 0.0574039;
  783. $solLongitude = $solAnomoly + 0.0334405 * sin($solAnomoly);
  784. $solLongitude += 4.93289 + 3.49066E-4 * sin(2 * $solAnomoly);
  785. // get quadrant
  786. $solLongitude = $this->_range($solLongitude, $fullCircle);
  787. if (($solLongitude / $quarterCircle) - intval($solLongitude / $quarterCircle) == 0) {
  788. $solLongitude += 4.84814E-6;
  789. }
  790. // solar ascension
  791. $solAscension = sin($solLongitude) / cos($solLongitude);
  792. $solAscension = atan2(0.91746 * $solAscension, 1);
  793. // adjust quadrant
  794. if ($solLongitude > $threeQuarterCircle) {
  795. $solAscension += $fullCircle;
  796. } else if ($solLongitude > $quarterCircle) {
  797. $solAscension += $halfCircle;
  798. }
  799. // solar declination
  800. $solDeclination = 0.39782 * sin($solLongitude);
  801. $solDeclination /= sqrt(-$solDeclination * $solDeclination + 1);
  802. $solDeclination = atan2($solDeclination, 1);
  803. $solHorizon = $horizon - sin($solDeclination) * sin($radLatitude);
  804. $solHorizon /= cos($solDeclination) * cos($radLatitude);
  805. // midnight sun, always night
  806. if (abs($solHorizon) > 1) {
  807. return false;
  808. }
  809. $solHorizon /= sqrt(-$solHorizon * $solHorizon + 1);
  810. $solHorizon = $quarterCircle - atan2($solHorizon, 1);
  811. if ($rise) {
  812. $solHorizon = $fullCircle - $solHorizon;
  813. }
  814. // time calculation
  815. $localTime = $solHorizon + $solAscension - 0.0172028 * $radDay - 1.73364;
  816. $universalTime = $localTime - $radLongitude;
  817. // determinate quadrant
  818. $universalTime = $this->_range($universalTime, $fullCircle);
  819. // radiant to hours
  820. $universalTime *= 24 / $fullCircle;
  821. // convert to time
  822. $hour = intval($universalTime);
  823. $universalTime = ($universalTime - $hour) * 60;
  824. $min = intval($universalTime);
  825. $universalTime = ($universalTime - $min) * 60;
  826. $sec = intval($universalTime);
  827. return $this->mktime($hour, $min, $sec, $this->date('m', $this->_unixTimestamp),
  828. $this->date('j', $this->_unixTimestamp), $this->date('Y', $this->_unixTimestamp),
  829. -1, true);
  830. }
  831. /**
  832. * Sets a new timezone for calculation of $this object's gmt offset.
  833. * For a list of supported timezones look here: http://php.net/timezones
  834. * If no timezone can be detected or the given timezone is wrong UTC will be set.
  835. *
  836. * @param string $zone OPTIONAL timezone for date calculation; defaults to date_default_timezone_get()
  837. * @return Zend_Date_DateObject Provides fluent interface
  838. * @throws Zend_Date_Exception
  839. */
  840. public function setTimezone($zone = null)
  841. {
  842. $oldzone = @date_default_timezone_get();
  843. if ($zone === null) {
  844. $zone = $oldzone;
  845. }
  846. // throw an error on false input, but only if the new date extension is available
  847. if (function_exists('timezone_open')) {
  848. if (!@timezone_open($zone)) {
  849. require_once 'Zend/Date/Exception.php';
  850. throw new Zend_Date_Exception("timezone ($zone) is not a known timezone", $zone);
  851. }
  852. }
  853. // this can generate an error if the date extension is not available and a false timezone is given
  854. $result = @date_default_timezone_set($zone);
  855. if ($result === true) {
  856. $this->_offset = mktime(0, 0, 0, 1, 2, 1970) - gmmktime(0, 0, 0, 1, 2, 1970);
  857. $this->_timezone = $zone;
  858. }
  859. date_default_timezone_set($oldzone);
  860. if (($zone == 'UTC') or ($zone == 'GMT')) {
  861. $this->_dst = false;
  862. } else {
  863. $this->_dst = true;
  864. }
  865. return $this;
  866. }
  867. /**
  868. * Return the timezone of $this object.
  869. * The timezone is initially set when the object is instantiated.
  870. *
  871. * @return string actual set timezone string
  872. */
  873. public function getTimezone()
  874. {
  875. return $this->_timezone;
  876. }
  877. /**
  878. * Return the offset to GMT of $this object's timezone.
  879. * The offset to GMT is initially set when the object is instantiated using the currently,
  880. * in effect, default timezone for PHP functions.
  881. *
  882. * @return integer seconds difference between GMT timezone and timezone when object was instantiated
  883. */
  884. public function getGmtOffset()
  885. {
  886. $date = $this->getDateParts($this->getUnixTimestamp(), true);
  887. $zone = @date_default_timezone_get();
  888. $result = @date_default_timezone_set($this->_timezone);
  889. if ($result === true) {
  890. $offset = $this->mktime($date['hours'], $date['minutes'], $date['seconds'],
  891. $date['mon'], $date['mday'], $date['year'], false)
  892. - $this->mktime($date['hours'], $date['minutes'], $date['seconds'],
  893. $date['mon'], $date['mday'], $date['year'], true);
  894. }
  895. date_default_timezone_set($zone);
  896. return $offset;
  897. }
  898. }