PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/adodb/adodb-time.inc.php

https://bitbucket.org/hky/bytehoard2
PHP | 984 lines | 504 code | 98 blank | 382 comment | 194 complexity | 26c658fb4f116cc25e9332bcbe344eef MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /**
  3. ADOdb Date Library, part of the ADOdb abstraction library
  4. Download: http://php.weblogs.com/adodb_date_time_library
  5. PHP native date functions use integer timestamps for computations.
  6. Because of this, dates are restricted to the years 1901-2038 on Unix
  7. and 1970-2038 on Windows due to integer overflow for dates beyond
  8. those years. This library overcomes these limitations by replacing the
  9. native function's signed integers (normally 32-bits) with PHP floating
  10. point numbers (normally 64-bits).
  11. Dates from 100 A.D. to 3000 A.D. and later
  12. have been tested. The minimum is 100 A.D. as <100 will invoke the
  13. 2 => 4 digit year conversion. The maximum is billions of years in the
  14. future, but this is a theoretical limit as the computation of that year
  15. would take too long with the current implementation of adodb_mktime().
  16. This library replaces native functions as follows:
  17. <pre>
  18. getdate() with adodb_getdate()
  19. date() with adodb_date()
  20. gmdate() with adodb_gmdate()
  21. mktime() with adodb_mktime()
  22. gmmktime() with adodb_gmmktime()
  23. </pre>
  24. The parameters are identical, except that adodb_date() accepts a subset
  25. of date()'s field formats. Mktime() will convert from local time to GMT,
  26. and date() will convert from GMT to local time, but daylight savings is
  27. not handled currently.
  28. This library is independant of the rest of ADOdb, and can be used
  29. as standalone code.
  30. PERFORMANCE
  31. For high speed, this library uses the native date functions where
  32. possible, and only switches to PHP code when the dates fall outside
  33. the 32-bit signed integer range.
  34. GREGORIAN CORRECTION
  35. Pope Gregory shortened October of A.D. 1582 by ten days. Thursday,
  36. October 4, 1582 (Julian) was followed immediately by Friday, October 15,
  37. 1582 (Gregorian).
  38. Since 0.06, we handle this correctly, so:
  39. adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582)
  40. == 24 * 3600 (1 day)
  41. =============================================================================
  42. COPYRIGHT
  43. (c) 2003-2004 John Lim and released under BSD-style license except for code by
  44. jackbbs, which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year
  45. and originally found at http://www.php.net/manual/en/function.mktime.php
  46. =============================================================================
  47. BUG REPORTS
  48. These should be posted to the ADOdb forums at
  49. http://phplens.com/lens/lensforum/topics.php?id=4
  50. =============================================================================
  51. FUNCTION DESCRIPTIONS
  52. FUNCTION adodb_getdate($date=false)
  53. Returns an array containing date information, as getdate(), but supports
  54. dates greater than 1901 to 2038.
  55. FUNCTION adodb_date($fmt, $timestamp = false)
  56. Convert a timestamp to a formatted local date. If $timestamp is not defined, the
  57. current timestamp is used. Unlike the function date(), it supports dates
  58. outside the 1901 to 2038 range.
  59. The format fields that adodb_date supports:
  60. <pre>
  61. a - "am" or "pm"
  62. A - "AM" or "PM"
  63. d - day of the month, 2 digits with leading zeros; i.e. "01" to "31"
  64. D - day of the week, textual, 3 letters; e.g. "Fri"
  65. F - month, textual, long; e.g. "January"
  66. g - hour, 12-hour format without leading zeros; i.e. "1" to "12"
  67. G - hour, 24-hour format without leading zeros; i.e. "0" to "23"
  68. h - hour, 12-hour format; i.e. "01" to "12"
  69. H - hour, 24-hour format; i.e. "00" to "23"
  70. i - minutes; i.e. "00" to "59"
  71. j - day of the month without leading zeros; i.e. "1" to "31"
  72. l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"
  73. L - boolean for whether it is a leap year; i.e. "0" or "1"
  74. m - month; i.e. "01" to "12"
  75. M - month, textual, 3 letters; e.g. "Jan"
  76. n - month without leading zeros; i.e. "1" to "12"
  77. O - Difference to Greenwich time in hours; e.g. "+0200"
  78. Q - Quarter, as in 1, 2, 3, 4
  79. r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200"
  80. s - seconds; i.e. "00" to "59"
  81. S - English ordinal suffix for the day of the month, 2 characters;
  82. i.e. "st", "nd", "rd" or "th"
  83. t - number of days in the given month; i.e. "28" to "31"
  84. T - Timezone setting of this machine; e.g. "EST" or "MDT"
  85. U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  86. w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)
  87. Y - year, 4 digits; e.g. "1999"
  88. y - year, 2 digits; e.g. "99"
  89. z - day of the year; i.e. "0" to "365"
  90. Z - timezone offset in seconds (i.e. "-43200" to "43200").
  91. The offset for timezones west of UTC is always negative,
  92. and for those east of UTC is always positive.
  93. </pre>
  94. Unsupported:
  95. <pre>
  96. B - Swatch Internet time
  97. I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
  98. W - ISO-8601 week number of year, weeks starting on Monday
  99. </pre>
  100. FUNCTION adodb_date2($fmt, $isoDateString = false)
  101. Same as adodb_date, but 2nd parameter accepts iso date, eg.
  102. adodb_date2('d-M-Y H:i','2003-12-25 13:01:34');
  103. FUNCTION adodb_gmdate($fmt, $timestamp = false)
  104. Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the
  105. current timestamp is used. Unlike the function date(), it supports dates
  106. outside the 1901 to 2038 range.
  107. FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year])
  108. Converts a local date to a unix timestamp. Unlike the function mktime(), it supports
  109. dates outside the 1901 to 2038 range. All parameters are optional.
  110. FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year])
  111. Converts a gmt date to a unix timestamp. Unlike the function gmmktime(), it supports
  112. dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters
  113. are currently compulsory.
  114. =============================================================================
  115. NOTES
  116. Useful url for generating test timestamps:
  117. http://www.4webhelp.net/us/timestamp.php
  118. Possible future optimizations include
  119. a. Using an algorithm similar to Plauger's in "The Standard C Library"
  120. (page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not
  121. work outside 32-bit signed range, so i decided not to implement it.
  122. b. Iterate over a block of years (say 12) when searching for the
  123. correct year.
  124. c. Implement daylight savings, which looks awfully complicated, see
  125. http://webexhibits.org/daylightsaving/
  126. CHANGELOG
  127. - 21 Dec 2004 0.17
  128. In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false.
  129. Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro.
  130. - 17 Nov 2004 0.16
  131. Removed intval typecast in adodb_mktime() for secs, allowing:
  132. adodb_mktime(0,0,0 + 2236672153,1,1,1934);
  133. Suggested by Ryan.
  134. - 18 July 2004 0.15
  135. All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory.
  136. This brings it more in line with mktime (still not identical).
  137. - 23 June 2004 0.14
  138. Allow you to define your own daylights savings function, adodb_daylight_sv.
  139. If the function is defined (somewhere in an include), then you can correct for daylights savings.
  140. In this example, we apply daylights savings in June or July, adding one hour. This is extremely
  141. unrealistic as it does not take into account time-zone, geographic location, current year.
  142. function adodb_daylight_sv(&$arr, $is_gmt)
  143. {
  144. if ($is_gmt) return;
  145. $m = $arr['mon'];
  146. if ($m == 6 || $m == 7) $arr['hours'] += 1;
  147. }
  148. This is only called by adodb_date() and not by adodb_mktime().
  149. The format of $arr is
  150. Array (
  151. [seconds] => 0
  152. [minutes] => 0
  153. [hours] => 0
  154. [mday] => 1 # day of month, eg 1st day of the month
  155. [mon] => 2 # month (eg. Feb)
  156. [year] => 2102
  157. [yday] => 31 # days in current year
  158. [leap] => # true if leap year
  159. [ndays] => 28 # no of days in current month
  160. )
  161. - 28 Apr 2004 0.13
  162. Fixed adodb_date to properly support $is_gmt. Thx to Dimitar Angelov.
  163. - 20 Mar 2004 0.12
  164. Fixed month calculation error in adodb_date. 2102-June-01 appeared as 2102-May-32.
  165. - 26 Oct 2003 0.11
  166. Because of daylight savings problems (some systems apply daylight savings to
  167. January!!!), changed adodb_get_gmt_diff() to ignore daylight savings.
  168. - 9 Aug 2003 0.10
  169. Fixed bug with dates after 2038.
  170. See http://phplens.com/lens/lensforum/msgs.php?id=6980
  171. - 1 July 2003 0.09
  172. Added support for Q (Quarter).
  173. Added adodb_date2(), which accepts ISO date in 2nd param
  174. - 3 March 2003 0.08
  175. Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS
  176. if you want PHP to handle negative timestamps between 1901 to 1969.
  177. - 27 Feb 2003 0.07
  178. All negative numbers handled by adodb now because of RH 7.3+ problems.
  179. See http://bugs.php.net/bug.php?id=20048&edit=2
  180. - 4 Feb 2003 0.06
  181. Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates
  182. are now correctly handled.
  183. - 29 Jan 2003 0.05
  184. Leap year checking differs under Julian calendar (pre 1582). Also
  185. leap year code optimized by checking for most common case first.
  186. We also handle month overflow correctly in mktime (eg month set to 13).
  187. Day overflow for less than one month's days is supported.
  188. - 28 Jan 2003 0.04
  189. Gregorian correction handled. In PHP5, we might throw an error if
  190. mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10.
  191. Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582.
  192. - 27 Jan 2003 0.03
  193. Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION.
  194. Fixed calculation of days since start of year for <1970.
  195. - 27 Jan 2003 0.02
  196. Changed _adodb_getdate() to inline leap year checking for better performance.
  197. Fixed problem with time-zones west of GMT +0000.
  198. - 24 Jan 2003 0.01
  199. First implementation.
  200. */
  201. /* Initialization */
  202. /*
  203. Version Number
  204. */
  205. define('ADODB_DATE_VERSION',0.17);
  206. /*
  207. We check for Windows as only +ve ints are accepted as dates on Windows.
  208. Apparently this problem happens also with Linux, RH 7.3 and later!
  209. glibc-2.2.5-34 and greater has been changed to return -1 for dates <
  210. 1970. This used to work. The problem exists with RedHat 7.3 and 8.0
  211. echo (mktime(0, 0, 0, 1, 1, 1960)); // prints -1
  212. References:
  213. http://bugs.php.net/bug.php?id=20048&edit=2
  214. http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html
  215. */
  216. if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1);
  217. function adodb_date_test_date($y1,$m)
  218. {
  219. //print " $y1/$m ";
  220. $t = adodb_mktime(0,0,0,$m,13,$y1);
  221. if ("$y1-$m-13 00:00:00" != adodb_date('Y-n-d H:i:s',$t)) {
  222. print "<b>$y1 error</b><br>";
  223. return false;
  224. }
  225. return true;
  226. }
  227. /**
  228. Test Suite
  229. */
  230. function adodb_date_test()
  231. {
  232. error_reporting(E_ALL);
  233. print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION. "</h4>";
  234. @set_time_limit(0);
  235. $fail = false;
  236. // This flag disables calling of PHP native functions, so we can properly test the code
  237. if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1);
  238. $t = adodb_mktime(0,0,0);
  239. if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'<br>';
  240. $t = adodb_mktime(0,0,0,6,1,2102);
  241. if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';
  242. $t = adodb_mktime(0,0,0,2,1,2102);
  243. if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';
  244. print "<p>Testing gregorian <=> julian conversion<p>";
  245. $t = adodb_mktime(0,0,0,10,11,1492);
  246. //http://www.holidayorigins.com/html/columbus_day.html - Friday check
  247. if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing<br>';
  248. $t = adodb_mktime(0,0,0,2,29,1500);
  249. if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years<br>';
  250. $t = adodb_mktime(0,0,0,2,29,1700);
  251. if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years<br>';
  252. print adodb_mktime(0,0,0,10,4,1582).' ';
  253. print adodb_mktime(0,0,0,10,15,1582);
  254. $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582));
  255. if ($diff != 3600*24) print " <b>Error in gregorian correction = ".($diff/3600/24)." days </b><br>";
  256. print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : '<b>Error</b>')."<br>";
  257. print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : '<b>Error</b>')."<br>";
  258. print "<p>Testing overflow<p>";
  259. $t = adodb_mktime(0,0,0,3,33,1965);
  260. if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1 <br>';
  261. $t = adodb_mktime(0,0,0,4,33,1971);
  262. if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2 <br>';
  263. $t = adodb_mktime(0,0,0,1,60,1965);
  264. if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).' <br>';
  265. $t = adodb_mktime(0,0,0,12,32,1965);
  266. if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).' <br>';
  267. $t = adodb_mktime(0,0,0,12,63,1965);
  268. if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).' <br>';
  269. $t = adodb_mktime(0,0,0,13,3,1965);
  270. if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1 <br>';
  271. print "Testing 2-digit => 4-digit year conversion<p>";
  272. if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000<br>";
  273. if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010<br>";
  274. if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020<br>";
  275. if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030<br>";
  276. if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940<br>";
  277. if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950<br>";
  278. if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990<br>";
  279. // Test string formating
  280. print "<p>Testing date formating</p>";
  281. $fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C822 r s t U w y Y z Z 2003';
  282. $s1 = date($fmt,0);
  283. $s2 = adodb_date($fmt,0);
  284. if ($s1 != $s2) {
  285. print " date() 0 failed<br>$s1<br>$s2<br>";
  286. }
  287. flush();
  288. for ($i=100; --$i > 0; ) {
  289. $ts = 3600.0*((rand()%60000)+(rand()%60000))+(rand()%60000);
  290. $s1 = date($fmt,$ts);
  291. $s2 = adodb_date($fmt,$ts);
  292. //print "$s1 <br>$s2 <p>";
  293. $pos = strcmp($s1,$s2);
  294. if (($s1) != ($s2)) {
  295. for ($j=0,$k=strlen($s1); $j < $k; $j++) {
  296. if ($s1[$j] != $s2[$j]) {
  297. print substr($s1,$j).' ';
  298. break;
  299. }
  300. }
  301. print "<b>Error date(): $ts<br><pre>
  302. &nbsp; \"$s1\" (date len=".strlen($s1).")
  303. &nbsp; \"$s2\" (adodb_date len=".strlen($s2).")</b></pre><br>";
  304. $fail = true;
  305. }
  306. $a1 = getdate($ts);
  307. $a2 = adodb_getdate($ts);
  308. $rez = array_diff($a1,$a2);
  309. if (sizeof($rez)>0) {
  310. print "<b>Error getdate() $ts</b><br>";
  311. print_r($a1);
  312. print "<br>";
  313. print_r($a2);
  314. print "<p>";
  315. $fail = true;
  316. }
  317. }
  318. // Test generation of dates outside 1901-2038
  319. print "<p>Testing random dates between 100 and 4000</p>";
  320. adodb_date_test_date(100,1);
  321. for ($i=100; --$i >= 0;) {
  322. $y1 = 100+rand(0,1970-100);
  323. $m = rand(1,12);
  324. adodb_date_test_date($y1,$m);
  325. $y1 = 3000-rand(0,3000-1970);
  326. adodb_date_test_date($y1,$m);
  327. }
  328. print '<p>';
  329. $start = 1960+rand(0,10);
  330. $yrs = 12;
  331. $i = 365.25*86400*($start-1970);
  332. $offset = 36000+rand(10000,60000);
  333. $max = 365*$yrs*86400;
  334. $lastyear = 0;
  335. // we generate a timestamp, convert it to a date, and convert it back to a timestamp
  336. // and check if the roundtrip broke the original timestamp value.
  337. print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: ";
  338. $cnt = 0;
  339. for ($max += $i; $i < $max; $i += $offset) {
  340. $ret = adodb_date('m,d,Y,H,i,s',$i);
  341. $arr = explode(',',$ret);
  342. if ($lastyear != $arr[2]) {
  343. $lastyear = $arr[2];
  344. print " $lastyear ";
  345. flush();
  346. }
  347. $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]);
  348. if ($i != $newi) {
  349. print "Error at $i, adodb_mktime returned $newi ($ret)";
  350. $fail = true;
  351. break;
  352. }
  353. $cnt += 1;
  354. }
  355. echo "Tested $cnt dates<br>";
  356. if (!$fail) print "<p>Passed !</p>";
  357. else print "<p><b>Failed</b> :-(</p>";
  358. }
  359. /**
  360. Returns day of week, 0 = Sunday,... 6=Saturday.
  361. Algorithm from PEAR::Date_Calc
  362. */
  363. function adodb_dow($year, $month, $day)
  364. {
  365. /*
  366. Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and
  367. proclaimed that from that time onwards 3 days would be dropped from the calendar
  368. every 400 years.
  369. Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian).
  370. */
  371. if ($year <= 1582) {
  372. if ($year < 1582 ||
  373. ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3;
  374. else
  375. $greg_correction = 0;
  376. } else
  377. $greg_correction = 0;
  378. if($month > 2)
  379. $month -= 2;
  380. else {
  381. $month += 10;
  382. $year--;
  383. }
  384. $day = floor((13 * $month - 1) / 5) +
  385. $day + ($year % 100) +
  386. floor(($year % 100) / 4) +
  387. floor(($year / 100) / 4) - 2 *
  388. floor($year / 100) + 77 + $greg_correction;
  389. return $day - 7 * floor($day / 7);
  390. }
  391. /**
  392. Checks for leap year, returns true if it is. No 2-digit year check. Also
  393. handles julian calendar correctly.
  394. */
  395. function _adodb_is_leap_year($year)
  396. {
  397. if ($year % 4 != 0) return false;
  398. if ($year % 400 == 0) {
  399. return true;
  400. // if gregorian calendar (>1582), century not-divisible by 400 is not leap
  401. } else if ($year > 1582 && $year % 100 == 0 ) {
  402. return false;
  403. }
  404. return true;
  405. }
  406. /**
  407. checks for leap year, returns true if it is. Has 2-digit year check
  408. */
  409. function adodb_is_leap_year($year)
  410. {
  411. return _adodb_is_leap_year(adodb_year_digit_check($year));
  412. }
  413. /**
  414. Fix 2-digit years. Works for any century.
  415. Assumes that if 2-digit is more than 30 years in future, then previous century.
  416. */
  417. function adodb_year_digit_check($y)
  418. {
  419. if ($y < 100) {
  420. $yr = (integer) date("Y");
  421. $century = (integer) ($yr /100);
  422. if ($yr%100 > 50) {
  423. $c1 = $century + 1;
  424. $c0 = $century;
  425. } else {
  426. $c1 = $century;
  427. $c0 = $century - 1;
  428. }
  429. $c1 *= 100;
  430. // if 2-digit year is less than 30 years in future, set it to this century
  431. // otherwise if more than 30 years in future, then we set 2-digit year to the prev century.
  432. if (($y + $c1) < $yr+30) $y = $y + $c1;
  433. else $y = $y + $c0*100;
  434. }
  435. return $y;
  436. }
  437. /**
  438. get local time zone offset from GMT
  439. */
  440. function adodb_get_gmt_diff()
  441. {
  442. static $TZ;
  443. if (isset($TZ)) return $TZ;
  444. $TZ = mktime(0,0,0,1,2,1970,0) - gmmktime(0,0,0,1,2,1970,0);
  445. return $TZ;
  446. }
  447. /**
  448. Returns an array with date info.
  449. */
  450. function adodb_getdate($d=false,$fast=false)
  451. {
  452. if ($d === false) return getdate();
  453. if (!defined('ADODB_TEST_DATES')) {
  454. if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  455. if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer
  456. return @getdate($d);
  457. }
  458. }
  459. return _adodb_getdate($d);
  460. }
  461. /**
  462. Low-level function that returns the getdate() array. We have a special
  463. $fast flag, which if set to true, will return fewer array values,
  464. and is much faster as it does not calculate dow, etc.
  465. */
  466. function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
  467. {
  468. $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff());
  469. $_day_power = 86400;
  470. $_hour_power = 3600;
  471. $_min_power = 60;
  472. if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction
  473. $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
  474. $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
  475. $d366 = $_day_power * 366;
  476. $d365 = $_day_power * 365;
  477. if ($d < 0) {
  478. if ($is_gmt) $origd = $d;
  479. // The valid range of a 32bit signed timestamp is typically from
  480. // Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT
  481. for ($a = 1970 ; --$a >= 0;) {
  482. $lastd = $d;
  483. if ($leaf = _adodb_is_leap_year($a)) $d += $d366;
  484. else $d += $d365;
  485. if ($d >= 0) {
  486. $year = $a;
  487. break;
  488. }
  489. }
  490. $secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd;
  491. $d = $lastd;
  492. $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal;
  493. for ($a = 13 ; --$a > 0;) {
  494. $lastd = $d;
  495. $d += $mtab[$a] * $_day_power;
  496. if ($d >= 0) {
  497. $month = $a;
  498. $ndays = $mtab[$a];
  499. break;
  500. }
  501. }
  502. $d = $lastd;
  503. $day = $ndays + ceil(($d+1) / ($_day_power));
  504. $d += ($ndays - $day+1)* $_day_power;
  505. $hour = floor($d/$_hour_power);
  506. } else {
  507. for ($a = 1970 ;; $a++) {
  508. $lastd = $d;
  509. if ($leaf = _adodb_is_leap_year($a)) $d -= $d366;
  510. else $d -= $d365;
  511. if ($d < 0) {
  512. $year = $a;
  513. break;
  514. }
  515. }
  516. $secsInYear = $lastd;
  517. $d = $lastd;
  518. $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal;
  519. for ($a = 1 ; $a <= 12; $a++) {
  520. $lastd = $d;
  521. $d -= $mtab[$a] * $_day_power;
  522. if ($d < 0) {
  523. $month = $a;
  524. $ndays = $mtab[$a];
  525. break;
  526. }
  527. }
  528. $d = $lastd;
  529. $day = ceil(($d+1) / $_day_power);
  530. $d = $d - ($day-1) * $_day_power;
  531. $hour = floor($d /$_hour_power);
  532. }
  533. $d -= $hour * $_hour_power;
  534. $min = floor($d/$_min_power);
  535. $secs = $d - $min * $_min_power;
  536. if ($fast) {
  537. return array(
  538. 'seconds' => $secs,
  539. 'minutes' => $min,
  540. 'hours' => $hour,
  541. 'mday' => $day,
  542. 'mon' => $month,
  543. 'year' => $year,
  544. 'yday' => floor($secsInYear/$_day_power),
  545. 'leap' => $leaf,
  546. 'ndays' => $ndays
  547. );
  548. }
  549. $dow = adodb_dow($year,$month,$day);
  550. return array(
  551. 'seconds' => $secs,
  552. 'minutes' => $min,
  553. 'hours' => $hour,
  554. 'mday' => $day,
  555. 'wday' => $dow,
  556. 'mon' => $month,
  557. 'year' => $year,
  558. 'yday' => floor($secsInYear/$_day_power),
  559. 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  560. 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  561. 0 => $origd
  562. );
  563. }
  564. function adodb_gmdate($fmt,$d=false)
  565. {
  566. return adodb_date($fmt,$d,true);
  567. }
  568. // accepts unix timestamp and iso date format in $d
  569. function adodb_date2($fmt, $d=false, $is_gmt=false)
  570. {
  571. if ($d !== false) {
  572. if (!preg_match(
  573. "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
  574. ($d), $rr)) return adodb_date($fmt,false,$is_gmt);
  575. if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt);
  576. // h-m-s-MM-DD-YY
  577. if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  578. else $d = @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
  579. }
  580. return adodb_date($fmt,$d,$is_gmt);
  581. }
  582. /**
  583. Return formatted date based on timestamp $d
  584. */
  585. function adodb_date($fmt,$d=false,$is_gmt=false)
  586. {
  587. static $daylight;
  588. if ($d === false) return ($is_gmt)? @gmdate($fmt): @date($fmt);
  589. if (!defined('ADODB_TEST_DATES')) {
  590. if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  591. if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer
  592. return ($is_gmt)? @gmdate($fmt,$d): @date($fmt,$d);
  593. }
  594. }
  595. $_day_power = 86400;
  596. $arr = _adodb_getdate($d,true,$is_gmt);
  597. if (!isset($daylight)) $daylight = function_exists('adodb_daylight_sv');
  598. if ($daylight) adodb_daylight_sv($arr, $is_gmt);
  599. $year = $arr['year'];
  600. $month = $arr['mon'];
  601. $day = $arr['mday'];
  602. $hour = $arr['hours'];
  603. $min = $arr['minutes'];
  604. $secs = $arr['seconds'];
  605. $max = strlen($fmt);
  606. $dates = '';
  607. /*
  608. at this point, we have the following integer vars to manipulate:
  609. $year, $month, $day, $hour, $min, $secs
  610. */
  611. for ($i=0; $i < $max; $i++) {
  612. switch($fmt[$i]) {
  613. case 'T': $dates .= date('T');break;
  614. // YEAR
  615. case 'L': $dates .= $arr['leap'] ? '1' : '0'; break;
  616. case 'r': // Thu, 21 Dec 2000 16:01:07 +0200
  617. $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', '
  618. . ($day<10?' '.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' ';
  619. if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour;
  620. if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min;
  621. if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs;
  622. $gmt = adodb_get_gmt_diff();
  623. $dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break;
  624. case 'Y': $dates .= $year; break;
  625. case 'y': $dates .= substr($year,strlen($year)-2,2); break;
  626. // MONTH
  627. case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break;
  628. case 'Q': $dates .= ($month+3)>>2; break;
  629. case 'n': $dates .= $month; break;
  630. case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break;
  631. case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break;
  632. // DAY
  633. case 't': $dates .= $arr['ndays']; break;
  634. case 'z': $dates .= $arr['yday']; break;
  635. case 'w': $dates .= adodb_dow($year,$month,$day); break;
  636. case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break;
  637. case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break;
  638. case 'j': $dates .= $day; break;
  639. case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break;
  640. case 'S':
  641. $d10 = $day % 10;
  642. if ($d10 == 1) $dates .= 'st';
  643. else if ($d10 == 2 && $day != 12) $dates .= 'nd';
  644. else if ($d10 == 3) $dates .= 'rd';
  645. else $dates .= 'th';
  646. break;
  647. // HOUR
  648. case 'Z':
  649. $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff(); break;
  650. case 'O':
  651. $gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff();
  652. $dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break;
  653. case 'H':
  654. if ($hour < 10) $dates .= '0'.$hour;
  655. else $dates .= $hour;
  656. break;
  657. case 'h':
  658. if ($hour > 12) $hh = $hour - 12;
  659. else {
  660. if ($hour == 0) $hh = '12';
  661. else $hh = $hour;
  662. }
  663. if ($hh < 10) $dates .= '0'.$hh;
  664. else $dates .= $hh;
  665. break;
  666. case 'G':
  667. $dates .= $hour;
  668. break;
  669. case 'g':
  670. if ($hour > 12) $hh = $hour - 12;
  671. else {
  672. if ($hour == 0) $hh = '12';
  673. else $hh = $hour;
  674. }
  675. $dates .= $hh;
  676. break;
  677. // MINUTES
  678. case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break;
  679. // SECONDS
  680. case 'U': $dates .= $d; break;
  681. case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break;
  682. // AM/PM
  683. // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM
  684. case 'a':
  685. if ($hour>=12) $dates .= 'pm';
  686. else $dates .= 'am';
  687. break;
  688. case 'A':
  689. if ($hour>=12) $dates .= 'PM';
  690. else $dates .= 'AM';
  691. break;
  692. default:
  693. $dates .= $fmt[$i]; break;
  694. // ESCAPE
  695. case "\\":
  696. $i++;
  697. if ($i < $max) $dates .= $fmt[$i];
  698. break;
  699. }
  700. }
  701. return $dates;
  702. }
  703. /**
  704. Returns a timestamp given a GMT/UTC time.
  705. Note that $is_dst is not implemented and is ignored.
  706. */
  707. function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false)
  708. {
  709. return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true);
  710. }
  711. /**
  712. Return a timestamp given a local time. Originally by jackbbs.
  713. Note that $is_dst is not implemented and is ignored.
  714. Not a very fast algorithm - O(n) operation. Could be optimized to O(1).
  715. */
  716. function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false)
  717. {
  718. if (!defined('ADODB_TEST_DATES')) {
  719. if ($mon === false) {
  720. return $is_gmt? @gmmktime($hr,$min,$sec): @mktime($hr,$min,$sec);
  721. }
  722. // for windows, we don't check 1970 because with timezone differences,
  723. // 1 Jan 1970 could generate negative timestamp, which is illegal
  724. if (1971 < $year && $year < 2038
  725. || !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038)
  726. ) {
  727. return $is_gmt ?
  728. @gmmktime($hr,$min,$sec,$mon,$day,$year):
  729. @mktime($hr,$min,$sec,$mon,$day,$year);
  730. }
  731. }
  732. $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff();
  733. /*
  734. # disabled because some people place large values in $sec.
  735. # however we need it for $mon because we use an array...
  736. $hr = intval($hr);
  737. $min = intval($min);
  738. $sec = intval($sec);
  739. */
  740. $mon = intval($mon);
  741. $day = intval($day);
  742. $year = intval($year);
  743. $year = adodb_year_digit_check($year);
  744. if ($mon > 12) {
  745. $y = floor($mon / 12);
  746. $year += $y;
  747. $mon -= $y*12;
  748. }
  749. $_day_power = 86400;
  750. $_hour_power = 3600;
  751. $_min_power = 60;
  752. $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
  753. $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
  754. $_total_date = 0;
  755. if ($year >= 1970) {
  756. for ($a = 1970 ; $a <= $year; $a++) {
  757. $leaf = _adodb_is_leap_year($a);
  758. if ($leaf == true) {
  759. $loop_table = $_month_table_leaf;
  760. $_add_date = 366;
  761. } else {
  762. $loop_table = $_month_table_normal;
  763. $_add_date = 365;
  764. }
  765. if ($a < $year) {
  766. $_total_date += $_add_date;
  767. } else {
  768. for($b=1;$b<$mon;$b++) {
  769. $_total_date += $loop_table[$b];
  770. }
  771. }
  772. }
  773. $_total_date +=$day-1;
  774. $ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different;
  775. } else {
  776. for ($a = 1969 ; $a >= $year; $a--) {
  777. $leaf = _adodb_is_leap_year($a);
  778. if ($leaf == true) {
  779. $loop_table = $_month_table_leaf;
  780. $_add_date = 366;
  781. } else {
  782. $loop_table = $_month_table_normal;
  783. $_add_date = 365;
  784. }
  785. if ($a > $year) { $_total_date += $_add_date;
  786. } else {
  787. for($b=12;$b>$mon;$b--) {
  788. $_total_date += $loop_table[$b];
  789. }
  790. }
  791. }
  792. $_total_date += $loop_table[$mon] - $day;
  793. $_day_time = $hr * $_hour_power + $min * $_min_power + $sec;
  794. $_day_time = $_day_power - $_day_time;
  795. $ret = -( $_total_date * $_day_power + $_day_time - $gmt_different);
  796. if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction
  797. else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582.
  798. }
  799. //print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret;
  800. return $ret;
  801. }
  802. ?>