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).
12 * Dates from 100 A.D. to 3000 A.D. and later have been tested.
13 * The minimum is 100 A.D. as <100 will invoke the 2 => 4 digit year
14 * conversion. The maximum is billions of years in the future, but this
15 * is a theoretical limit as the computation of that year would take too
16 * long with the current implementation of adodb_mktime().
18 * Replaces native functions as follows:
19 * - getdate() with adodb_getdate()
20 * - date() with adodb_date()
21 * - gmdate() with adodb_gmdate()
22 * - mktime() with adodb_mktime()
23 * - gmmktime() with adodb_gmmktime()
24 * - strftime() with adodb_strftime()
25 * - strftime() with adodb_gmstrftime()
27 * The parameters are identical, except that adodb_date() accepts a subset
28 * of date()'s field formats. Mktime() will convert from local time to GMT,
29 * and date() will convert from GMT to local time, but daylight savings is
30 * not handled currently.
32 * To improve performance, the native date functions are used whenever
33 * possible, the library only switches to PHP code when the dates fall outside
34 * of the 32-bit signed integer range.
36 * This library is independent of the rest of ADOdb, and can be used
39 * GREGORIAN CORRECTION
41 * Pope Gregory shortened October of A.D. 1582 by ten days. Thursday,
42 * October 4, 1582 (Julian) was followed immediately by Friday, October 15,
43 * 1582 (Gregorian). We handle this correctly, so:
44 * adodb_mktime(0, 0, 0, 10, 15, 1582) - adodb_mktime(0, 0, 0, 10, 4, 1582)
45 * == 24 * 3600 (1 day)
47 * This file is part of ADOdb, a Database Abstraction Layer library for PHP.
50 * @link https://adodb.org Project's web site and documentation
51 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker
53 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
54 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
55 * any later version. This means you can use it in proprietary products.
56 * See the LICENSE.md file distributed with this source code for details.
57 * @license BSD-3-Clause
58 * @license LGPL-2.1-or-later
60 * @copyright 2003-2013 John Lim
61 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
65 =============================================================================
69 ** FUNCTION adodb_time()
71 Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) as an unsigned integer.
73 ** FUNCTION adodb_getdate($date=false)
75 Returns an array containing date information, as getdate(), but supports
76 dates greater than 1901 to 2038. The local date/time format is derived from a
77 heuristic the first time adodb_getdate is called.
80 ** FUNCTION adodb_date($fmt, $timestamp = false)
82 Convert a timestamp to a formatted local date. If $timestamp is not defined, the
83 current timestamp is used. Unlike the function date(), it supports dates
84 outside the 1901 to 2038 range.
86 The format fields that adodb_date supports:
91 d - day of the month, 2 digits with leading zeros; i.e. "01" to "31"
92 D - day of the week, textual, 3 letters; e.g. "Fri"
93 F - month, textual, long; e.g. "January"
94 g - hour, 12-hour format without leading zeros; i.e. "1" to "12"
95 G - hour, 24-hour format without leading zeros; i.e. "0" to "23"
96 h - hour, 12-hour format; i.e. "01" to "12"
97 H - hour, 24-hour format; i.e. "00" to "23"
98 i - minutes; i.e. "00" to "59"
99 j - day of the month without leading zeros; i.e. "1" to "31"
100 l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"
101 L - boolean for whether it is a leap year; i.e. "0" or "1"
102 m - month; i.e. "01" to "12"
103 M - month, textual, 3 letters; e.g. "Jan"
104 n - month without leading zeros; i.e. "1" to "12"
105 O - Difference to Greenwich time in hours; e.g. "+0200"
106 Q - Quarter, as in 1, 2, 3, 4
107 r - RFC 2822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200"
108 s - seconds; i.e. "00" to "59"
109 S - English ordinal suffix for the day of the month, 2 characters;
110 i.e. "st", "nd", "rd" or "th"
111 t - number of days in the given month; i.e. "28" to "31"
112 T - Timezone setting of this machine; e.g. "EST" or "MDT"
113 U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
114 w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)
115 Y - year, 4 digits; e.g. "1999"
116 y - year, 2 digits; e.g. "99"
117 z - day of the year; i.e. "0" to "365"
118 Z - timezone offset in seconds (i.e. "-43200" to "43200").
119 The offset for timezones west of UTC is always negative,
120 and for those east of UTC is always positive.
125 B - Swatch Internet time
126 I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
127 W - ISO-8601 week number of year, weeks starting on Monday
132 ** FUNCTION adodb_date2($fmt, $isoDateString = false)
133 Same as adodb_date, but 2nd parameter accepts iso date, eg.
135 adodb_date2('d-M-Y H:i','2003-12-25 13:01:34');
138 ** FUNCTION adodb_gmdate($fmt, $timestamp = false)
140 Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the
141 current timestamp is used. Unlike the function date(), it supports dates
142 outside the 1901 to 2038 range.
145 ** FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year])
147 Converts a local date to a unix timestamp. Unlike the function mktime(), it supports
148 dates outside the 1901 to 2038 range. All parameters are optional.
151 ** FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year])
153 Converts a gmt date to a unix timestamp. Unlike the function gmmktime(), it supports
154 dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters
155 are currently compulsory.
157 ** FUNCTION adodb_gmstrftime($fmt, $timestamp = false)
158 Convert a timestamp to a formatted GMT date.
160 ** FUNCTION adodb_strftime($fmt, $timestamp = false)
162 Convert a timestamp to a formatted local date. Internally converts $fmt into
163 adodb_date format, then echo result.
165 For best results, you can define the local date format yourself. Define a global
166 variable $ADODB_DATE_LOCALE which is an array, 1st element is date format using
167 adodb_date syntax, and 2nd element is the time format, also in adodb_date syntax.
169 eg. $ADODB_DATE_LOCALE = array('d/m/Y','H:i:s');
171 Supported format codes:
174 %a - abbreviated weekday name according to the current locale
175 %A - full weekday name according to the current locale
176 %b - abbreviated month name according to the current locale
177 %B - full month name according to the current locale
178 %c - preferred date and time representation for the current locale
179 %d - day of the month as a decimal number (range 01 to 31)
180 %D - same as %m/%d/%y
181 %e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')
183 %H - hour as a decimal number using a 24-hour clock (range 00 to 23)
184 %I - hour as a decimal number using a 12-hour clock (range 01 to 12)
185 %m - month as a decimal number (range 01 to 12)
186 %M - minute as a decimal number
187 %n - newline character
188 %p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
189 %r - time in a.m. and p.m. notation
190 %R - time in 24 hour notation
191 %S - second as a decimal number
193 %T - current time, equal to %H:%M:%S
194 %x - preferred date representation for the current locale without the time
195 %X - preferred time representation for the current locale without the date
196 %y - year as a decimal number without a century (range 00 to 99)
197 %Y - year as a decimal number including the century
198 %Z - time zone or name or abbreviation
199 %% - a literal `%' character
204 %C - century number (the year divided by 100 and truncated to an integer, range 00 to 99)
205 %g - like %G, but without the century.
206 %G - The 4-digit year corresponding to the ISO week number (see %V).
207 This has the same format and value as %Y, except that if the ISO week number belongs
208 to the previous or next year, that year is used instead.
209 %j - day of the year as a decimal number (range 001 to 366)
210 %u - weekday as a decimal number [1,7], with 1 representing Monday
211 %U - week number of the current year as a decimal number, starting
212 with the first Sunday as the first day of the first week
213 %V - The ISO 8601:1988 week number of the current year as a decimal number,
214 range 01 to 53, where week 1 is the first week that has at least 4 days in the
215 current year, and with Monday as the first day of the week. (Use %G or %g for
216 the year component that corresponds to the week number for the specified timestamp.)
217 %w - day of the week as a decimal, Sunday being 0
218 %W - week number of the current year as a decimal number, starting with the
219 first Monday as the first day of the first week
222 =============================================================================
226 Useful url for generating test timestamps:
227 http://www.4webhelp.net/us/timestamp.php
229 Possible future optimizations include
231 a. Using an algorithm similar to Plauger's in "The Standard C Library"
232 (page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not
233 work outside 32-bit signed range, so i decided not to implement it.
235 b. Implement daylight savings, which looks awfully complicated, see
236 http://webexhibits.org/daylightsaving/
241 Added adodb_time() which returns current time. If > 2038, will return as float
244 Changed adodb_date to be symmetric with adodb_mktime. See $jan1_71. fix for bc.
247 Changed adodb_get_gm_diff to use DateTimeZone().
250 * Bug in 0.32 fix for hour handling. Fixed.
253 * Now adodb_mktime(0,0,0,12+$m,20,2040) works properly.
256 * Now adodb_mktime(0,0,0,24,1,2037) works correctly.
259 Added PHP 5.2.0 compatibility fixes.
260 * gmtime behaviour for 1970 has changed. We use the actual date if it is between 1970 to 2038 to get the
261 * timezone, otherwise we use the current year as the baseline to retrieve the timezone.
262 * Also the timezone's in php 5.2.* support historical data better, eg. if timezone today was +8, but
263 in 1970 it was +7:30, then php 5.2 return +7:30, while this library will use +8.
267 Changed strftime() locale detection, because some locales prepend the day of week to the date when %c is used.
270 PHP5 compat: when we detect PHP5, the RFC2822 format for gmt 0000hrs is changed from -0000 to +0000.
271 In PHP4, we will still use -0000 for 100% compat with PHP4.
274 In adodb_date2(), $is_gmt not supported properly. Fixed.
277 In PHP 4.3.11, the 'r' format has changed. Leading 0 in day is added. Changed for compat.
278 Added support for negative months in adodb_mktime().
281 Added limited strftime/gmstrftime support. x10 improvement in performance of adodb_date().
284 In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false.
285 Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro.
288 Removed intval typecast in adodb_mktime() for secs, allowing:
289 adodb_mktime(0,0,0 + 2236672153,1,1,1934);
293 All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory.
294 This brings it more in line with mktime (still not identical).
298 Allow you to define your own daylights savings function, adodb_daylight_sv.
299 If the function is defined (somewhere in an include), then you can correct for daylights savings.
301 In this example, we apply daylights savings in June or July, adding one hour. This is extremely
302 unrealistic as it does not take into account time-zone, geographic location, current year.
304 function adodb_daylight_sv(&$arr, $is_gmt)
308 if ($m == 6 || $m == 7) $arr['hours'] += 1;
311 This is only called by adodb_date() and not by adodb_mktime().
313 The format of $arr is
318 [mday] => 1 # day of month, eg 1st day of the month
319 [mon] => 2 # month (eg. Feb)
321 [yday] => 31 # days in current year
322 [leap] => # true if leap year
323 [ndays] => 28 # no of days in current month
328 Fixed adodb_date to properly support $is_gmt. Thx to Dimitar Angelov.
331 Fixed month calculation error in adodb_date. 2102-June-01 appeared as 2102-May-32.
334 Because of daylight savings problems (some systems apply daylight savings to
335 January!!!), changed adodb_get_gmt_diff() to ignore daylight savings.
338 Fixed bug with dates after 2038.
339 See PHPLens Issue No: 6980
342 Added support for Q (Quarter).
343 Added adodb_date2(), which accepts ISO date in 2nd param
346 Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS
347 if you want PHP to handle negative timestamps between 1901 to 1969.
350 All negative numbers handled by adodb now because of RH 7.3+ problems.
351 See http://bugs.php.net/bug.php?id=20048&edit=2
354 Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates
355 are now correctly handled.
359 Leap year checking differs under Julian calendar (pre 1582). Also
360 leap year code optimized by checking for most common case first.
362 We also handle month overflow correctly in mktime (eg month set to 13).
364 Day overflow for less than one month's days is supported.
368 Gregorian correction handled. In PHP5, we might throw an error if
369 mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10.
370 Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582.
374 Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION.
375 Fixed calculation of days since start of year for <1970.
379 Changed _adodb_getdate() to inline leap year checking for better performance.
380 Fixed problem with time-zones west of GMT +0000.
384 First implementation.
393 define('ADODB_DATE_VERSION',0.35);
396 This code was originally for windows. But apparently this problem happens
397 also with Linux, RH 7.3 and later!
399 glibc-2.2.5-34 and greater has been changed to return -1 for dates <
400 1970. This used to work. The problem exists with RedHat 7.3 and 8.0
401 echo (mktime(0, 0, 0, 1, 1, 1960)); // prints -1
404 http://bugs.php.net/bug.php?id=20048&edit=2
405 http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html
408 if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1);
410 if (!DEFINED('ADODB_FUTURE_DATE_CUTOFF_YEARS'))
411 DEFINE('ADODB_FUTURE_DATE_CUTOFF_YEARS',200);
413 function adodb_date_test_date($y1,$m,$d=13)
415 $h = round(rand()%
24);
416 $t = adodb_mktime($h,0,0,$m,$d,$y1);
417 $rez = adodb_date('Y-n-j H:i:s',$t);
418 if ($h == 0) $h = '00';
419 else if ($h < 10) $h = '0'.$h;
420 if ("$y1-$m-$d $h:00:00" != $rez) {
421 print "<b>$y1 error, expected=$y1-$m-$d $h:00:00, adodb=$rez</b><br>";
427 function adodb_date_test_strftime($fmt)
429 $s1 = strftime($fmt);
430 $s2 = adodb_strftime($fmt);
432 if ($s1 == $s2) return true;
434 echo "error for $fmt, strftime=$s1, adodb=$s2<br>";
441 function adodb_date_test()
444 for ($m=-24; $m<=24; $m++
)
445 echo "$m :",adodb_date('d-m-Y',adodb_mktime(0,0,0,1+
$m,20,2040)),"<br>";
447 error_reporting(E_ALL
);
448 print "<h4>Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION
.' PHP='.PHP_VERSION
."</h4>";
452 // This flag disables calling of PHP native functions, so we can properly test the code
453 if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1);
458 $fmt = 'Y-m-d H:i:s';
460 echo 'adodb: ',adodb_date($fmt,$t),'<br>';
461 echo 'php : ',date($fmt,$t),'<br>';
464 adodb_date_test_strftime('%Y %m %x %X');
465 adodb_date_test_strftime("%A %d %B %Y");
466 adodb_date_test_strftime("%H %M S");
468 $t = adodb_mktime(0,0,0);
469 if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'<br>';
471 $t = adodb_mktime(0,0,0,6,1,2102);
472 if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';
474 $t = adodb_mktime(0,0,0,2,1,2102);
475 if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'<br>';
478 print "<p>Testing gregorian <=> julian conversion<p>";
479 $t = adodb_mktime(0,0,0,10,11,1492);
480 //http://www.holidayorigins.com/html/columbus_day.html - Friday check
481 if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing<br>';
483 $t = adodb_mktime(0,0,0,2,29,1500);
484 if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years<br>';
486 $t = adodb_mktime(0,0,0,2,29,1700);
487 if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years<br>';
489 print adodb_mktime(0,0,0,10,4,1582).' ';
490 print adodb_mktime(0,0,0,10,15,1582);
491 $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582));
492 if ($diff != 3600*24) print " <b>Error in gregorian correction = ".($diff/3600/24)." days </b><br>";
494 print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ?
'Fri' : '<b>Error</b>')."<br>";
495 print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ?
'Thu' : '<b>Error</b>')."<br>";
497 print "<p>Testing overflow<p>";
499 $t = adodb_mktime(0,0,0,3,33,1965);
500 if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1 <br>';
501 $t = adodb_mktime(0,0,0,4,33,1971);
502 if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2 <br>';
503 $t = adodb_mktime(0,0,0,1,60,1965);
504 if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).' <br>';
505 $t = adodb_mktime(0,0,0,12,32,1965);
506 if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).' <br>';
507 $t = adodb_mktime(0,0,0,12,63,1965);
508 if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).' <br>';
509 $t = adodb_mktime(0,0,0,13,3,1965);
510 if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1 <br>';
512 print "Testing 2-digit => 4-digit year conversion<p>";
513 if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000<br>";
514 if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010<br>";
515 if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020<br>";
516 if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030<br>";
517 if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940<br>";
518 if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950<br>";
519 if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990<br>";
521 // Test string formatting
522 print "<p>Testing date formatting</p>";
524 $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\C2822 r s t U w y Y z Z 2003';
526 $s2 = adodb_date($fmt,0);
528 print " date() 0 failed<br>$s1<br>$s2<br>";
531 for ($i=100; --$i > 0; ) {
533 $ts = 3600.0*((rand()%60000
)+
(rand()%60000
))+
(rand()%60000
);
534 $s1 = date($fmt,$ts);
535 $s2 = adodb_date($fmt,$ts);
536 //print "$s1 <br>$s2 <p>";
537 $pos = strcmp($s1,$s2);
539 if (($s1) != ($s2)) {
540 for ($j=0,$k=strlen($s1); $j < $k; $j++
) {
541 if ($s1[$j] != $s2[$j]) {
542 print substr($s1,$j).' ';
546 print "<b>Error date(): $ts<br><pre>
547 \"$s1\" (date len=".strlen($s1).")
548 \"$s2\" (adodb_date len=".strlen($s2).")</b></pre><br>";
553 $a2 = adodb_getdate($ts);
554 $rez = array_diff($a1,$a2);
555 if (sizeof($rez)>0) {
556 print "<b>Error getdate() $ts</b><br>";
565 // Test generation of dates outside 1901-2038
566 print "<p>Testing random dates between 100 and 4000</p>";
567 adodb_date_test_date(100,1);
568 for ($i=100; --$i >= 0;) {
569 $y1 = 100+
rand(0,1970-100);
571 adodb_date_test_date($y1,$m);
573 $y1 = 3000-rand(0,3000-1970);
574 adodb_date_test_date($y1,$m);
577 $start = 1960+
rand(0,10);
579 $i = 365.25*86400*($start-1970);
580 $offset = 36000+
rand(10000,60000);
581 $max = 365*$yrs*86400;
584 // we generate a timestamp, convert it to a date, and convert it back to a timestamp
585 // and check if the roundtrip broke the original timestamp value.
586 print "Testing $start to ".($start+
$yrs).", or $max seconds, offset=$offset: ";
588 for ($max +
= $i; $i < $max; $i +
= $offset) {
589 $ret = adodb_date('m,d,Y,H,i,s',$i);
590 $arr = explode(',',$ret);
591 if ($lastyear != $arr[2]) {
596 $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]);
598 print "Error at $i, adodb_mktime returned $newi ($ret)";
604 echo "Tested $cnt dates<br>";
605 if (!$fail) print "<p>Passed !</p>";
606 else print "<p><b>Failed</b> :-(</p>";
609 function adodb_time()
612 return $d->format('U');
616 Returns day of week, 0 = Sunday,... 6=Saturday.
617 Algorithm from PEAR::Date_Calc
619 function adodb_dow($year, $month, $day)
622 Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and
623 proclaimed that from that time onwards 3 days would be dropped from the calendar
626 Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian).
630 ($year == 1582 && ($month < 10 ||
($month == 10 && $day < 15)))) $greg_correction = 3;
632 $greg_correction = 0;
634 $greg_correction = 0;
643 $day = floor((13 * $month - 1) / 5) +
644 $day +
($year %
100) +
645 floor(($year %
100) / 4) +
646 floor(($year / 100) / 4) - 2 *
647 floor($year / 100) +
77 +
$greg_correction;
649 return $day - 7 * floor($day / 7);
654 Checks for leap year, returns true if it is. No 2-digit year check. Also
655 handles julian calendar correctly.
657 function _adodb_is_leap_year($year)
659 if ($year %
4 != 0) return false;
661 if ($year %
400 == 0) {
663 // if gregorian calendar (>1582), century not-divisible by 400 is not leap
664 } else if ($year > 1582 && $year %
100 == 0 ) {
673 checks for leap year, returns true if it is. Has 2-digit year check
675 function adodb_is_leap_year($year)
677 return _adodb_is_leap_year(adodb_year_digit_check($year));
681 Fix 2-digit years. Works for any century.
682 Assumes that if 2-digit is more than 30 years in future, then previous century.
684 function adodb_year_digit_check($y)
688 $yr = (integer) date("Y");
689 $century = (integer) ($yr /100);
699 // if 2-digit year is less than 30 years in future, set it to this century
700 // otherwise if more than 30 years in future, then we set 2-digit year to the prev century.
701 if (($y +
$c1) < $yr+
30) $y = $y +
$c1;
702 else $y = $y +
$c0*100;
707 function adodb_get_gmt_diff_ts($ts)
709 if (0 <= $ts && $ts <= 0x7FFFFFFF) { // check if number in 32-bit signed range) {
714 return adodb_get_gmt_diff($y,$m,$d);
716 return adodb_get_gmt_diff(false,false,false);
722 get local time zone offset from GMT. Does not handle historical timezones before 1970.
724 function adodb_get_gmt_diff($y,$m,$d)
728 if (!defined('ADODB_TEST_DATES')) $y = false;
729 else if ($y < 1970 ||
$y >= 2038) $y = false;
732 $dt = new DateTime();
733 $dt->setISODate($y,$m,$d);
735 $tzo = new DateTimeZone(date_default_timezone_get());
736 # $tzt = timezone_transitions_get( $tzo );
738 return -$tzo->getOffset($dt);
740 if (isset($TZ)) return $TZ;
743 if (function_exists('date_default_timezone_get') && function_exists('timezone_offset_get')) {
744 $tzonename = date_default_timezone_get();
746 $tobj = new DateTimeZone($tzonename);
747 $TZ = -timezone_offset_get($tobj,new DateTime("now",$tzo));
751 if (empty($TZ)) $TZ = mktime(0,0,0,12,2,$y) - gmmktime(0,0,0,12,2,$y);
757 Returns an array with date info.
759 function adodb_getdate($d=false,$fast=false)
761 if ($d === false) return getdate();
762 if (!defined('ADODB_TEST_DATES')) {
763 if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
764 if (!defined('ADODB_NO_NEGATIVE_TS') ||
$d >= 0) // if windows, must be +ve integer
768 return _adodb_getdate($d);
772 // generate $YRS table for _adodb_getdate()
773 function adodb_date_gentable($out=true)
776 for ($i=1970; $i >= 1600; $i-=10) {
777 $s = adodb_gmmktime(0,0,0,1,1,$i);
778 echo "$i => $s,<br>";
781 adodb_date_gentable();
783 for ($i=1970; $i > 1500; $i--) {
786 adodb_date_test_date($i,1,1);
792 $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
793 $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
795 function adodb_validdate($y,$m,$d)
797 global $_month_table_normal,$_month_table_leaf;
799 if (_adodb_is_leap_year($y)) $marr = $_month_table_leaf;
800 else $marr = $_month_table_normal;
802 if ($m > 12 ||
$m < 1) return false;
804 if ($d > 31 ||
$d < 1) return false;
806 if ($marr[$m] < $d) return false;
808 if ($y < 1000 ||
$y > 3000) return false;
814 Low-level function that returns the getdate() array. We have a special
815 $fast flag, which if set to true, will return fewer array values,
816 and is much faster as it does not calculate dow, etc.
818 function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
821 global $_month_table_normal,$_month_table_leaf, $_adodb_last_date_call_failed;
823 $_adodb_last_date_call_failed = false;
825 $d = $origd - ($is_gmt ?
0 : adodb_get_gmt_diff_ts($origd));
830 $cutoffDate = time() +
(60 * 60 * 24 * 365 * ADODB_FUTURE_DATE_CUTOFF_YEARS
);
832 if ($d > $cutoffDate)
835 $_adodb_last_date_call_failed = true;
838 if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction
840 $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
841 $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
843 $d366 = $_day_power * 366;
844 $d365 = $_day_power * 365;
848 if (empty($YRS)) $YRS = array(
881 1650 => -10098172800,
882 1640 => -10413792000,
883 1630 => -10729324800,
884 1620 => -11044944000,
885 1610 => -11360476800,
886 1600 => -11676096000);
888 if ($is_gmt) $origd = $d;
889 // The valid range of a 32bit signed timestamp is typically from
890 // Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT
893 # old algorithm iterates through all years. new algorithm does it in
898 for ($a = 1970 ; --$a >= 0;) {
901 if ($leaf = _adodb_is_leap_year($a)) $d += $d366;
913 foreach($YRS as $year => $secs) {
923 if (!isset($a)) $a = $lastyear;
925 //echo ' yr=',$a,' ', $d,'.';
930 if ($leaf = _adodb_is_leap_year($a)) $d +
= $d366;
940 $secsInYear = 86400 * ($leaf ?
366 : 365) +
$lastd;
943 $mtab = ($leaf) ?
$_month_table_leaf : $_month_table_normal;
944 for ($a = 13 ; --$a > 0;) {
946 $d +
= $mtab[$a] * $_day_power;
955 $day = $ndays +
ceil(($d+
1) / ($_day_power));
957 $d +
= ($ndays - $day+
1)* $_day_power;
958 $hour = floor($d/$_hour_power);
961 for ($a = 1970 ;; $a++
) {
964 if ($leaf = _adodb_is_leap_year($a)) $d -= $d366;
971 $secsInYear = $lastd;
973 $mtab = ($leaf) ?
$_month_table_leaf : $_month_table_normal;
974 for ($a = 1 ; $a <= 12; $a++
) {
976 $d -= $mtab[$a] * $_day_power;
984 $day = ceil(($d+
1) / $_day_power);
985 $d = $d - ($day-1) * $_day_power;
986 $hour = floor($d /$_hour_power);
989 $d -= $hour * $_hour_power;
990 $min = floor($d/$_min_power);
991 $secs = $d - $min * $_min_power;
1000 'yday' => floor($secsInYear/$_day_power),
1007 $dow = adodb_dow($year,$month,$day);
1017 'yday' => floor($secsInYear/$_day_power),
1018 'weekday' => gmdate('l',$_day_power*(3+
$dow)),
1019 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
1025 * Compute timezone offset.
1027 * @param int $gmt Time offset from GMT, in seconds
1028 * @param bool $ignored Param leftover from removed PHP4-compatibility code
1029 * kept to avoid altering function signature.
1032 function adodb_tz_offset($gmt, $ignored=true)
1034 $zhrs = abs($gmt) / 3600;
1035 $hrs = floor($zhrs);
1036 return sprintf('%s%02d%02d', ($gmt <= 0) ?
'+' : '-', $hrs, ($zhrs - $hrs) * 60);
1040 function adodb_gmdate($fmt,$d=false)
1042 return adodb_date($fmt,$d,true);
1045 // accepts unix timestamp and iso date format in $d
1046 function adodb_date2($fmt, $d=false, $is_gmt=false)
1050 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
1051 ($d), $rr)) return adodb_date($fmt,false,$is_gmt);
1053 if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt);
1056 if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1],false,$is_gmt);
1057 else $d = @adodb_mktime
($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1],false,$is_gmt);
1060 return adodb_date($fmt,$d,$is_gmt);
1065 Return formatted date based on timestamp $d
1067 function adodb_date($fmt,$d=false,$is_gmt=false)
1072 if (!isset($daylight)) {
1073 $daylight = function_exists('adodb_daylight_sv');
1074 if (empty($jan1_1971)) $jan1_1971 = mktime(0,0,0,1,1,1971); // we only use date() when > 1970 as adodb_mktime() only uses mktime() when > 1970
1077 if ($d === false) return ($is_gmt)? @gmdate
($fmt): @date
($fmt);
1078 if (!defined('ADODB_TEST_DATES')) {
1081 * Format 'Q' is an ADOdb custom format, not supported in PHP
1082 * so if there is a 'Q' in the format, we force it to use our
1083 * function. There is a trivial overhead in this
1086 if ((abs($d) <= 0x7FFFFFFF) && strpos($fmt,'Q') === false)
1087 { // check if number in 32-bit signed range
1089 if (!defined('ADODB_NO_NEGATIVE_TS') ||
$d >= $jan1_1971) // if windows, must be +ve integer
1090 return ($is_gmt)? @gmdate
($fmt,$d): @date
($fmt,$d);
1094 $_day_power = 86400;
1096 $arr = _adodb_getdate($d,true,$is_gmt);
1098 if ($daylight) adodb_daylight_sv($arr, $is_gmt);
1100 $year = $arr['year'];
1101 $month = $arr['mon'];
1102 $day = $arr['mday'];
1103 $hour = $arr['hours'];
1104 $min = $arr['minutes'];
1105 $secs = $arr['seconds'];
1107 $max = strlen($fmt);
1111 at this point, we have the following integer vars to manipulate:
1112 $year, $month, $day, $hour, $min, $secs
1114 for ($i=0; $i < $max; $i++
) {
1117 $dates .= date('e');
1120 $dt = new DateTime();
1121 $dt->SetDate($year,$month,$day);
1122 $dates .= $dt->Format('T');
1125 case 'L': $dates .= $arr['leap'] ?
'1' : '0'; break;
1126 case 'r': // Thu, 21 Dec 2000 16:01:07 +0200
1128 // 4.3.11 uses '04 Jun 2004'
1129 // 4.3.8 uses ' 4 Jun 2004'
1130 $dates .= gmdate('D',$_day_power*(3+
adodb_dow($year,$month,$day))).', '
1131 . ($day<10?
'0'.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' ';
1133 if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour;
1135 if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min;
1137 if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs;
1139 $gmt = adodb_get_gmt_diff($year,$month,$day);
1141 $dates .= ' '.adodb_tz_offset($gmt);
1144 case 'Y': $dates .= $year; break;
1145 case 'y': $dates .= substr($year,strlen($year)-2,2); break;
1147 case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break;
1149 $dates .= ceil($month / 3);
1151 case 'n': $dates .= $month; break;
1152 case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break;
1153 case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break;
1155 case 't': $dates .= $arr['ndays']; break;
1156 case 'z': $dates .= $arr['yday']; break;
1157 case 'w': $dates .= adodb_dow($year,$month,$day); break;
1159 $dates .= sprintf('%02d',ceil( $arr['yday'] / 7) - 1);
1161 case 'l': $dates .= gmdate('l',$_day_power*(3+
adodb_dow($year,$month,$day))); break;
1162 case 'D': $dates .= gmdate('D',$_day_power*(3+
adodb_dow($year,$month,$day))); break;
1163 case 'j': $dates .= $day; break;
1164 case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break;
1167 if ($d10 == 1) $dates .= 'st';
1168 else if ($d10 == 2 && $day != 12) $dates .= 'nd';
1169 else if ($d10 == 3) $dates .= 'rd';
1170 else $dates .= 'th';
1175 $dates .= ($is_gmt) ?
0 : -adodb_get_gmt_diff($year,$month,$day); break;
1177 $gmt = ($is_gmt) ?
0 : adodb_get_gmt_diff($year,$month,$day);
1179 $dates .= adodb_tz_offset($gmt);
1183 if ($hour < 10) $dates .= '0'.$hour;
1184 else $dates .= $hour;
1187 if ($hour > 12) $hh = $hour - 12;
1189 if ($hour == 0) $hh = '12';
1193 if ($hh < 10) $dates .= '0'.$hh;
1202 if ($hour > 12) $hh = $hour - 12;
1204 if ($hour == 0) $hh = '12';
1210 case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break;
1212 case 'U': $dates .= $d; break;
1213 case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break;
1215 // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM
1217 if ($hour>=12) $dates .= 'pm';
1218 else $dates .= 'am';
1221 if ($hour>=12) $dates .= 'PM';
1222 else $dates .= 'AM';
1225 $dates .= $fmt[$i]; break;
1229 if ($i < $max) $dates .= $fmt[$i];
1237 Returns a timestamp given a GMT/UTC time.
1238 Note that $is_dst is not implemented and is ignored.
1240 function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false)
1242 return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true);
1246 Return a timestamp given a local time. Originally by jackbbs.
1247 Note that $is_dst is not implemented and is ignored.
1249 Not a very fast algorithm - O(n) operation. Could be optimized to O(1).
1251 function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false)
1253 if (!defined('ADODB_TEST_DATES')) {
1255 if ($mon === false) {
1256 return $is_gmt? @gmmktime
($hr,$min,$sec): @mktime
($hr,$min,$sec);
1259 // for windows, we don't check 1970 because with timezone differences,
1260 // 1 Jan 1970 could generate negative timestamp, which is illegal
1261 $usephpfns = (1970 < $year && $year < 2038
1262 ||
!defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038)
1266 if ($usephpfns && ($year +
$mon/12+
$day/365.25+
$hr/(24*365.25) >= 2038)) $usephpfns = false;
1270 @gmmktime
($hr,$min,$sec,$mon,$day,$year):
1271 @mktime
($hr,$min,$sec,$mon,$day,$year);
1275 $gmt_different = ($is_gmt) ?
0 : adodb_get_gmt_diff($year,$mon,$day);
1278 # disabled because some people place large values in $sec.
1279 # however we need it for $mon because we use an array...
1281 $min = intval($min);
1282 $sec = intval($sec);
1284 $mon = intval($mon);
1285 $day = intval($day);
1286 $year = intval($year);
1289 $year = adodb_year_digit_check($year);
1292 $y = floor(($mon-1)/ 12);
1295 } else if ($mon < 1) {
1296 $y = ceil((1-$mon) / 12);
1301 $_day_power = 86400;
1302 $_hour_power = 3600;
1305 $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
1306 $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
1309 if ($year >= 1970) {
1310 for ($a = 1970 ; $a <= $year; $a++
) {
1311 $leaf = _adodb_is_leap_year($a);
1312 if ($leaf == true) {
1313 $loop_table = $_month_table_leaf;
1316 $loop_table = $_month_table_normal;
1320 $_total_date +
= $_add_date;
1322 for($b=1;$b<$mon;$b++
) {
1323 $_total_date +
= $loop_table[$b];
1327 $_total_date +
=$day-1;
1328 $ret = $_total_date * $_day_power +
$hr * $_hour_power +
$min * $_min_power +
$sec +
$gmt_different;
1331 for ($a = 1969 ; $a >= $year; $a--) {
1332 $leaf = _adodb_is_leap_year($a);
1333 if ($leaf == true) {
1334 $loop_table = $_month_table_leaf;
1337 $loop_table = $_month_table_normal;
1340 if ($a > $year) { $_total_date +
= $_add_date;
1342 for($b=12;$b>$mon;$b--) {
1343 $_total_date +
= $loop_table[$b];
1347 $_total_date +
= $loop_table[$mon] - $day;
1349 $_day_time = $hr * $_hour_power +
$min * $_min_power +
$sec;
1350 $_day_time = $_day_power - $_day_time;
1351 $ret = -( $_total_date * $_day_power +
$_day_time - $gmt_different);
1352 if ($ret < -12220185600) $ret +
= 10*86400; // if earlier than 5 Oct 1582 - gregorian correction
1353 else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582.
1355 //print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret;
1359 function adodb_gmstrftime($fmt, $ts=false)
1361 return adodb_strftime($fmt,$ts,true);
1364 // hack - convert to adodb_date
1365 function adodb_strftime($fmt, $ts=false,$is_gmt=false)
1367 global $ADODB_DATE_LOCALE;
1369 if (!defined('ADODB_TEST_DATES')) {
1370 if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
1371 if (!defined('ADODB_NO_NEGATIVE_TS') ||
$ts >= 0) // if windows, must be +ve integer
1372 return ($is_gmt)? @gmstrftime
($fmt,$ts): @strftime
($fmt,$ts);
1377 if (empty($ADODB_DATE_LOCALE)) {
1379 $tstr = strtoupper(gmstrftime('%c',31366800)); // 30 Dec 1970, 1 am
1380 $sep = substr($tstr,2,1);
1381 $hasAM = strrpos($tstr,'M') !== false;
1383 # see PHPLens Issue No: 14865 for reasoning, and changelog for version 0.24
1384 $dstr = gmstrftime('%x',31366800); // 30 Dec 1970, 1 am
1385 $sep = substr($dstr,2,1);
1386 $tstr = strtoupper(gmstrftime('%X',31366800)); // 30 Dec 1970, 1 am
1387 $hasAM = strrpos($tstr,'M') !== false;
1389 $ADODB_DATE_LOCALE = array();
1390 $ADODB_DATE_LOCALE[] = strncmp($tstr,'30',2) == 0 ?
'd'.$sep.'m'.$sep.'y' : 'm'.$sep.'d'.$sep.'y';
1391 $ADODB_DATE_LOCALE[] = ($hasAM) ?
'h:i:s a' : 'H:i:s';
1396 for ($i=0,$max = strlen($fmt); $i < $max; $i++
) {
1404 } else if ($inpct) {
1420 /* ignore format modifiers */
1424 case 'a': $fmtdate .= 'D'; break;
1425 case 'A': $fmtdate .= 'l'; break;
1427 case 'b': $fmtdate .= 'M'; break;
1428 case 'B': $fmtdate .= 'F'; break;
1429 case 'c': $fmtdate .= $ADODB_DATE_LOCALE[0].$ADODB_DATE_LOCALE[1]; break;
1430 case 'C': $fmtdate .= '\C?'; break; // century
1431 case 'd': $fmtdate .= 'd'; break;
1432 case 'D': $fmtdate .= 'm/d/y'; break;
1433 case 'e': $fmtdate .= 'j'; break;
1434 case 'g': $fmtdate .= '\g?'; break; //?
1435 case 'G': $fmtdate .= '\G?'; break; //?
1436 case 'H': $fmtdate .= 'H'; break;
1437 case 'I': $fmtdate .= 'h'; break;
1438 case 'j': $fmtdate .= '?z'; $parsej = true; break; // wrong as j=1-based, z=0-basd
1439 case 'm': $fmtdate .= 'm'; break;
1440 case 'M': $fmtdate .= 'i'; break;
1441 case 'n': $fmtdate .= "\n"; break;
1442 case 'p': $fmtdate .= 'a'; break;
1443 case 'r': $fmtdate .= 'h:i:s a'; break;
1444 case 'R': $fmtdate .= 'H:i:s'; break;
1445 case 'S': $fmtdate .= 's'; break;
1446 case 't': $fmtdate .= "\t"; break;
1447 case 'T': $fmtdate .= 'H:i:s'; break;
1448 case 'u': $fmtdate .= '?u'; $parseu = true; break; // wrong strftime=1-based, date=0-based
1449 case 'U': $fmtdate .= '?U'; $parseU = true; break;// wrong strftime=1-based, date=0-based
1450 case 'x': $fmtdate .= $ADODB_DATE_LOCALE[0]; break;
1451 case 'X': $fmtdate .= $ADODB_DATE_LOCALE[1]; break;
1452 case 'w': $fmtdate .= '?w'; $parseu = true; break; // wrong strftime=1-based, date=0-based
1453 case 'W': $fmtdate .= '?W'; $parseU = true; break;// wrong strftime=1-based, date=0-based
1454 case 'y': $fmtdate .= 'y'; break;
1455 case 'Y': $fmtdate .= 'Y'; break;
1456 case 'Z': $fmtdate .= 'T'; break;
1458 } else if (('A' <= ($ch) && ($ch) <= 'Z' ) ||
('a' <= ($ch) && ($ch) <= 'z' ))
1459 $fmtdate .= "\\".$ch;
1463 //echo "fmt=",$fmtdate,"<br>";
1464 if ($ts === false) $ts = time();
1465 $ret = adodb_date($fmtdate, $ts, $is_gmt);
1470 * Returns the status of the last date calculation and whether it exceeds
1471 * the limit of ADODB_FUTURE_DATE_CUTOFF_YEARS
1475 function adodb_last_date_status()
1477 global $_adodb_last_date_call_failed;
1479 return $_adodb_last_date_call_failed;