dolibarr 20.0.2
date.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2011 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2011-2015 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2017 Ferran Marcet <fmarcet@2byte.es>
6 * Copyright (C) 2018-2024 Charlene Benke <charlene@patas-monkey.com>
7 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 * or see https://www.gnu.org/
23 */
24
36function get_tz_array()
37{
38 $tzarray = array(
39 -11 => "Pacific/Pago_Pago",
40 -10 => "Pacific/Honolulu",
41 -9 => "America/Anchorage",
42 -8 => "America/Los_Angeles",
43 -7 => "America/Dawson_Creek",
44 -6 => "America/Chicago",
45 -5 => "America/Bogota",
46 -4 => "America/Asuncion",
47 -3 => "America/Araguaina",
48 -2 => "America/Noronha",
49 -1 => "Atlantic/Azores",
50 0 => "Europe/London",
51 1 => "Europe/Paris",
52 2 => "Europe/Helsinki",
53 3 => "Europe/Moscow",
54 4 => "Asia/Dubai",
55 5 => "Asia/Karachi",
56 6 => "Indian/Chagos",
57 7 => "Asia/Jakarta",
58 8 => "Asia/Hong_Kong",
59 9 => "Asia/Tokyo",
60 10 => "Australia/Sydney",
61 11 => "Pacific/Noumea",
62 12 => "Pacific/Auckland",
63 13 => "Pacific/Fakaofo",
64 14 => "Pacific/Kiritimati"
65 );
66 return $tzarray;
67}
68
69
76{
77 return @date_default_timezone_get();
78}
79
86function getServerTimeZoneInt($refgmtdate = 'now')
87{
88 if (method_exists('DateTimeZone', 'getOffset')) {
89 // Method 1 (include daylight)
90 $gmtnow = dol_now('gmt');
91 $yearref = dol_print_date($gmtnow, '%Y');
92 $monthref = dol_print_date($gmtnow, '%m');
93 $dayref = dol_print_date($gmtnow, '%d');
94 if ($refgmtdate == 'now') {
95 $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref;
96 } elseif ($refgmtdate == 'summer') {
97 $newrefgmtdate = $yearref.'-08-01';
98 } else {
99 $newrefgmtdate = $yearref.'-01-01';
100 }
101 $newrefgmtdate .= 'T00:00:00+00:00';
102 $localtz = new DateTimeZone(getServerTimeZoneString());
103 $localdt = new DateTime($newrefgmtdate, $localtz);
104 $tmp = -1 * $localtz->getOffset($localdt);
105 //print $refgmtdate.'='.$tmp;
106 } else {
107 $tmp = 0;
108 dol_print_error(null, 'PHP version must be 5.3+');
109 }
110 $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
111 return $tz;
112}
113
114
125function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
126{
127 if (empty($duration_value)) {
128 return $time;
129 }
130 if ($duration_unit == 's') {
131 return $time + ($duration_value);
132 }
133 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
134 return $time + (60 * $duration_value);
135 }
136 if ($duration_unit == 'h') {
137 return $time + (3600 * $duration_value);
138 }
139 if ($duration_unit == 'w') {
140 return $time + (3600 * 24 * 7 * $duration_value);
141 }
142
143 $deltastring = 'P';
144
145 if ($duration_value > 0) {
146 $deltastring .= abs($duration_value);
147 $sub = false;
148 }
149 if ($duration_value < 0) {
150 $deltastring .= abs($duration_value);
151 $sub = true;
152 }
153 if ($duration_unit == 'd') {
154 $deltastring .= "D";
155 }
156 if ($duration_unit == 'm') {
157 $deltastring .= "M";
158 }
159 if ($duration_unit == 'y') {
160 $deltastring .= "Y";
161 }
162
163 $date = new DateTime();
164 if (getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_GMT')) {
165 $date->setTimezone(new DateTimeZone('UTC'));
166 }
167 $date->setTimestamp($time);
168 $interval = new DateInterval($deltastring);
169
170 if ($sub) {
171 $date->sub($interval);
172 } else {
173 $date->add($interval);
174 }
175 //Change the behavior of PHP over data-interval when the result of this function is Feb 29 (non-leap years), 30 or Feb 31 (so php returns March 1, 2 or 3 respectively)
176 if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
177 $timeyear = (int) dol_print_date($time, '%Y');
178 $timemonth = (int) dol_print_date($time, '%m');
179 $timetotalmonths = (($timeyear * 12) + $timemonth);
180
181 $monthsexpected = ($timetotalmonths + $duration_value);
182
183 $newtime = $date->getTimestamp();
184
185 $newtimeyear = (int) dol_print_date($newtime, '%Y');
186 $newtimemonth = (int) dol_print_date($newtime, '%m');
187 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
188
189 if ($monthsexpected < $newtimetotalmonths) {
190 $newtimehours = (int) dol_print_date($newtime, '%H');
191 $newtimemins = (int) dol_print_date($newtime, '%M');
192 $newtimesecs = (int) dol_print_date($newtime, '%S');
193
194 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
195 $datelim -= (3600 * 24);
196
197 $date->setTimestamp($datelim);
198 }
199 }
200 return $date->getTimestamp();
201}
202
203
213function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
214{
215 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
216 return $iResult;
217}
218
219
242function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
243{
244 global $langs;
245
246 if (empty($lengthOfDay)) {
247 $lengthOfDay = 86400; // 1 day = 24 hours
248 }
249 if (empty($lengthOfWeek)) {
250 $lengthOfWeek = 7; // 1 week = 7 days
251 }
252 $nbHbyDay = $lengthOfDay / 3600;
253
254 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
255 if ((int) $iSecond === 0) {
256 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
257 }
258
259 $sTime = '';
260 $sDay = 0;
261 $sWeek = 0;
262
263 if ($iSecond >= $lengthOfDay) {
264 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
265 $sDay++;
266 $iSecond -= $lengthOfDay;
267 }
268 $dayTranslate = $langs->trans("Day");
269 if ($iSecond >= ($lengthOfDay * 2)) {
270 $dayTranslate = $langs->trans("Days");
271 }
272 }
273
274 if ($lengthOfWeek < 7) {
275 if ($sDay) {
276 if ($sDay >= $lengthOfWeek) {
277 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
278 $sDay = $sDay % $lengthOfWeek;
279 $weekTranslate = $langs->trans("DurationWeek");
280 if ($sWeek >= 2) {
281 $weekTranslate = $langs->trans("DurationWeeks");
282 }
283 $sTime .= $sWeek.' '.$weekTranslate.' ';
284 }
285 }
286 }
287 if ($sDay > 0) {
288 $dayTranslate = $langs->trans("Day");
289 if ($sDay > 1) {
290 $dayTranslate = $langs->trans("Days");
291 }
292 $sTime .= $sDay.' '.$langs->trans("d").' ';
293 }
294
295 if ($format == 'all') {
296 if ($iSecond || empty($sDay)) {
297 $sTime .= dol_print_date($iSecond, 'hourduration', true);
298 }
299 } elseif ($format == 'allhourminsec') {
300 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
301 } elseif ($format == 'allhourmin') {
302 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60)));
303 } elseif ($format == 'allhour') {
304 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600)));
305 }
306 } elseif ($format == 'hour') { // only hour part
307 $sTime = dol_print_date($iSecond, '%H', true);
308 } elseif ($format == 'fullhour') {
309 if (!empty($iSecond)) {
310 $iSecond = $iSecond / 3600;
311 } else {
312 $iSecond = 0;
313 }
314 $sTime = $iSecond;
315 } elseif ($format == 'min') { // only min part
316 $sTime = dol_print_date($iSecond, '%M', true);
317 } elseif ($format == 'sec') { // only sec part
318 $sTime = dol_print_date($iSecond, '%S', true);
319 } elseif ($format == 'month') { // only month part
320 $sTime = dol_print_date($iSecond, '%m', true);
321 } elseif ($format == 'year') { // only year part
322 $sTime = dol_print_date($iSecond, '%Y', true);
323 }
324 return trim($sTime);
325}
326
327
334function convertDurationtoHour($duration_value, $duration_unit)
335{
336 $result = 0;
337
338 if ($duration_unit == 's') {
339 $result = $duration_value / 3600;
340 }
341 if ($duration_unit == 'i' || $duration_unit == 'mn' || $duration_unit == 'min') {
342 $result = $duration_value / 60;
343 }
344 if ($duration_unit == 'h') {
345 $result = $duration_value;
346 }
347 if ($duration_unit == 'd') {
348 $result = $duration_value * 24;
349 }
350 if ($duration_unit == 'w') {
351 $result = $duration_value * 24 * 7;
352 }
353 if ($duration_unit == 'm') {
354 $result = $duration_value * 730.484;
355 }
356 if ($duration_unit == 'y') {
357 $result = $duration_value * 365 * 24;
358 }
359
360 return $result;
361}
362
378function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
379{
380 global $db;
381 $sqldate = '';
382
383 $day_date = intval($day_date);
384 $month_date = intval($month_date);
385 $year_date = intval($year_date);
386
387 if ($month_date > 0) {
388 if ($month_date > 12) { // protection for bad value of month
389 return " AND 1 = 2";
390 }
391 if ($year_date > 0 && empty($day_date)) {
392 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
393 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
394 } elseif ($year_date > 0 && !empty($day_date)) {
395 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
396 $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
397 } else {
398 // This case is not reliable on TZ, but we should not need it.
399 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
400 }
401 } elseif ($year_date > 0) {
402 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
403 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
404 }
405 return $sqldate;
406}
407
427function dol_stringtotime($string, $gm = 1)
428{
429 $reg = array();
430 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
431 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
432 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
433 // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
434 // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
435 $sday = (int) $reg[1];
436 $smonth = (int) $reg[2];
437 $syear = (int) $reg[3];
438 $shour = (int) $reg[4];
439 $smin = (int) $reg[5];
440 $ssec = (int) $reg[6];
441 if ($syear < 50) {
442 $syear += 1900;
443 }
444 if ($syear >= 50 && $syear < 100) {
445 $syear += 2000;
446 }
447 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
448 } elseif (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i', $string, $reg) // Convert date with format YYYY-MM-DDTHH:MM:SSZ (RFC3339)
449 || preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/i', $string, $reg) // Convert date with format YYYY-MM-DD HH:MM:SS
450 || preg_match('/^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})([0-9]{2})Z$/i', $string, $reg) // Convert date with format YYYYMMDDTHHMMSSZ
451 ) {
452 $syear = (int) $reg[1];
453 $smonth = (int) $reg[2];
454 $sday = (int) $reg[3];
455 $shour = (int) $reg[4];
456 $smin = (int) $reg[5];
457 $ssec = (int) $reg[6];
458 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
459 }
460
461 $string = preg_replace('/([^0-9])/i', '', $string);
462 $tmp = $string.'000000';
463 // Clean $gm
464 if ($gm === 1) {
465 $gm = 'gmt';
466 } elseif (empty($gm) || $gm === 'tzserver') {
467 $gm = 'tzserver';
468 }
469
470 $date = dol_mktime(substr($tmp, 8, 2), substr($tmp, 10, 2), substr($tmp, 12, 2), substr($tmp, 4, 2), substr($tmp, 6, 2), substr($tmp, 0, 4), $gm);
471 return $date;
472}
473
474
483function dol_get_prev_day($day, $month, $year)
484{
485 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
486 $time -= 24 * 60 * 60;
487 $tmparray = dol_getdate($time, true);
488 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
489}
490
499function dol_get_next_day($day, $month, $year)
500{
501 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
502 $time += 24 * 60 * 60;
503 $tmparray = dol_getdate($time, true);
504 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
505}
506
514function dol_get_prev_month($month, $year)
515{
516 if ($month == 1) {
517 $prev_month = 12;
518 $prev_year = $year - 1;
519 } else {
520 $prev_month = $month - 1;
521 $prev_year = $year;
522 }
523 return array('year' => $prev_year, 'month' => $prev_month);
524}
525
533function dol_get_next_month($month, $year)
534{
535 if ($month == 12) {
536 $next_month = 1;
537 $next_year = $year + 1;
538 } else {
539 $next_month = $month + 1;
540 $next_year = $year;
541 }
542 return array('year' => $next_year, 'month' => $next_month);
543}
544
554function dol_get_prev_week($day, $week, $month, $year)
555{
556 $tmparray = dol_get_first_day_week($day, $month, $year);
557
558 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
559 $time -= 24 * 60 * 60 * 7;
560 $tmparray = dol_getdate($time, true);
561 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
562}
563
573function dol_get_next_week($day, $week, $month, $year)
574{
575 $tmparray = dol_get_first_day_week($day, $month, $year);
576
577 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
578 $time += 24 * 60 * 60 * 7;
579 $tmparray = dol_getdate($time, true);
580
581 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
582}
583
595function dol_get_first_day($year, $month = 1, $gm = false)
596{
597 if ($year > 9999) {
598 return '';
599 }
600 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
601}
602
603
614function dol_get_last_day($year, $month = 12, $gm = false)
615{
616 if ($year > 9999) {
617 return '';
618 }
619 if ($month == 12) {
620 $month = 1;
621 $year += 1;
622 } else {
623 $month += 1;
624 }
625
626 // On se deplace au debut du mois suivant, et on retire un jour
627 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
628 $datelim -= (3600 * 24);
629
630 return $datelim;
631}
632
641function dol_get_last_hour($date, $gm = 'tzserver')
642{
643 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
644 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
645}
646
655function dol_get_first_hour($date, $gm = 'tzserver')
656{
657 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
658 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
659}
660
670function dol_get_first_day_week($day, $month, $year, $gm = false)
671{
672 global $conf;
673
674 //$day=2; $month=2; $year=2015;
675 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
676
677 //Checking conf of start week
678 $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
679
680 $tmparray = dol_getdate($date, true); // detail of current day
681
682 //Calculate days = offset from current day
683 $days = $start_week - $tmparray['wday'];
684 if ($days >= 1) {
685 $days = 7 - $days;
686 }
687 $days = abs($days);
688 $seconds = $days * 24 * 60 * 60;
689 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
690
691 //Get first day of week
692 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
693 $tmpday = idate("d", $tmpdaytms);
694
695 //Check first day of week is in same month than current day or not
696 if ($tmpday > $day) {
697 $prev_month = $month - 1;
698 $prev_year = $year;
699
700 if ($prev_month == 0) {
701 $prev_month = 12;
702 $prev_year = $year - 1;
703 }
704 } else {
705 $prev_month = $month;
706 $prev_year = $year;
707 }
708 $tmpmonth = $prev_month;
709 $tmpyear = $prev_year;
710
711 //Get first day of next week
712 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
713 $tmptime -= 24 * 60 * 60 * 7;
714 $tmparray = dol_getdate($tmptime, true);
715 $prev_day = $tmparray['mday'];
716
717 //Check prev day of week is in same month than first day or not
718 if ($prev_day > $tmpday) {
719 $prev_month = $month - 1;
720 $prev_year = $year;
721
722 if ($prev_month == 0) {
723 $prev_month = 12;
724 $prev_year = $year - 1;
725 }
726 }
727
728 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
729
730 return array('year' => $year, 'month' => $month, 'week' => $week, 'first_day' => $tmpday, 'first_month' => $tmpmonth, 'first_year' => $tmpyear, 'prev_year' => $prev_year, 'prev_month' => $prev_month, 'prev_day' => $prev_day);
731}
732
740function getGMTEasterDatetime($year)
741{
742 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
743 $days = easter_days($year); // Return number of days between 21 march and easter day.
744 $tmp = $base->add(new DateInterval("P{$days}D"));
745 return $tmp->getTimestamp();
746}
747
764function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
765{
766 global $conf, $db, $mysoc;
767
768 $nbFerie = 0;
769
770 // Check to ensure we use correct parameters
771 if (($timestampEnd - $timestampStart) % 86400 != 0) {
772 return 'Error Dates must use same hours and must be GMT dates';
773 }
774
775 if (empty($country_code)) {
776 $country_code = $mysoc->country_code;
777 }
778 if ($includemonday < 0) {
779 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
780 }
781 if ($includefriday < 0) {
782 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
783 }
784 if ($includesaturday < 0) {
785 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
786 }
787 if ($includesunday < 0) {
788 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
789 }
790
791 $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
792
793 if (empty($conf->cache['arrayOfActivePublicHolidays_'.$country_id])) {
794 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
795 $tmpArrayOfPublicHolidays = array();
796 $sql = "SELECT id, code, entity, fk_country, dayrule, year, month, day, active";
797 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
798 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
799 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
800
801 $resql = $db->query($sql);
802 if ($resql) {
803 $num_rows = $db->num_rows($resql);
804 $i = 0;
805 while ($i < $num_rows) {
806 $obj = $db->fetch_object($resql);
807 $tmpArrayOfPublicHolidays[$obj->id] = array('dayrule' => $obj->dayrule, 'year' => $obj->year, 'month' => $obj->month, 'day' => $obj->day);
808 $i++;
809 }
810 } else {
811 dol_syslog($db->lasterror(), LOG_ERR);
812 return 'Error sql '.$db->lasterror();
813 }
814
815 //var_dump($tmpArrayOfPublicHolidays);
816 $conf->cache['arrayOfActivePublicHolidays_'.$country_id] = $tmpArrayOfPublicHolidays;
817 }
818
819 $arrayOfPublicHolidays = $conf->cache['arrayOfActivePublicHolidays_'.$country_id];
820
821 $i = 0;
822 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
823 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
824 $ferie = false;
825 $specialdayrule = array();
826
827 $jour = (int) gmdate("d", $timestampStart);
828 $mois = (int) gmdate("m", $timestampStart);
829 $annee = (int) gmdate("Y", $timestampStart);
830
831 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
832 foreach ($arrayOfPublicHolidays as $entrypublicholiday) {
833 if (!empty($entrypublicholiday['dayrule']) && $entrypublicholiday['dayrule'] != 'date') { // For example 'easter', '...'
834 $specialdayrule[$entrypublicholiday['dayrule']] = $entrypublicholiday['dayrule'];
835 } else {
836 $match = 1;
837 if (!empty($entrypublicholiday['year']) && $entrypublicholiday['year'] != $annee) {
838 $match = 0;
839 }
840 if ($entrypublicholiday['month'] != $mois) {
841 $match = 0;
842 }
843 if ($entrypublicholiday['day'] != $jour) {
844 $match = 0;
845 }
846
847 if ($match) {
848 $ferie = true;
849 }
850 }
851
852 $i++;
853 }
854 //var_dump($specialdayrule)."\n";
855 //print "ferie=".$ferie."\n";
856
857 if (!$ferie) {
858 // Special dayrules
859 if (in_array('easter', $specialdayrule)) {
860 // Calculation for easter date
861 $date_paques = getGMTEasterDatetime($annee);
862 $jour_paques = gmdate("d", $date_paques);
863 $mois_paques = gmdate("m", $date_paques);
864 if ($jour_paques == $jour && $mois_paques == $mois) {
865 $ferie = true;
866 }
867 // Easter (sunday)
868 }
869
870 if (in_array('eastermonday', $specialdayrule)) {
871 // Calculation for the monday of easter date
872 $date_paques = getGMTEasterDatetime($annee);
873 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
874 $date_lundi_paques = $date_paques + (3600 * 24);
875 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
876 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
877 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
878 $ferie = true;
879 }
880 // Easter (monday)
881 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
882 }
883
884 //Good Friday
885 if (in_array('goodfriday', $specialdayrule)) {
886 // Pulls the date of Easter
887 $easter = getGMTEasterDatetime($annee);
888
889 // Calculates the date of Good Friday based on Easter
890 $date_good_friday = $easter - (2 * 3600 * 24);
891 $dom_good_friday = gmdate("d", $date_good_friday);
892 $month_good_friday = gmdate("m", $date_good_friday);
893
894 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
895 $ferie = true;
896 }
897 }
898
899 if (in_array('ascension', $specialdayrule)) {
900 // Calcul du jour de l'ascension (39 days after easter day)
901 $date_paques = getGMTEasterDatetime($annee);
902 $date_ascension = $date_paques + (3600 * 24 * 39);
903 $jour_ascension = gmdate("d", $date_ascension);
904 $mois_ascension = gmdate("m", $date_ascension);
905 if ($jour_ascension == $jour && $mois_ascension == $mois) {
906 $ferie = true;
907 }
908 // Ascension (thursday)
909 }
910
911 if (in_array('pentecost', $specialdayrule)) {
912 // Calculation of "Pentecote" (49 days after easter day)
913 $date_paques = getGMTEasterDatetime($annee);
914 $date_pentecote = $date_paques + (3600 * 24 * 49);
915 $jour_pentecote = gmdate("d", $date_pentecote);
916 $mois_pentecote = gmdate("m", $date_pentecote);
917 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
918 $ferie = true;
919 }
920 // "Pentecote" (sunday)
921 }
922 if (in_array('pentecotemonday', $specialdayrule)) {
923 // Calculation of "Pentecote" (49 days after easter day)
924 $date_paques = getGMTEasterDatetime($annee);
925 $date_pentecote = $date_paques + (3600 * 24 * 50);
926 $jour_pentecote = gmdate("d", $date_pentecote);
927 $mois_pentecote = gmdate("m", $date_pentecote);
928 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
929 $ferie = true;
930 }
931 // "Pentecote" (monday)
932 }
933
934 if (in_array('viernessanto', $specialdayrule)) {
935 // Viernes Santo
936 $date_paques = getGMTEasterDatetime($annee);
937 $date_viernes = $date_paques - (3600 * 24 * 2);
938 $jour_viernes = gmdate("d", $date_viernes);
939 $mois_viernes = gmdate("m", $date_viernes);
940 if ($jour_viernes == $jour && $mois_viernes == $mois) {
941 $ferie = true;
942 }
943 //Viernes Santo
944 }
945
946 if (in_array('fronleichnam', $specialdayrule)) {
947 // Fronleichnam (60 days after easter sunday)
948 $date_paques = getGMTEasterDatetime($annee);
949 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
950 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
951 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
952 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
953 $ferie = true;
954 }
955 // Fronleichnam
956 }
957
958 if (in_array('genevafast', $specialdayrule)) {
959 // Geneva fast in Switzerland (Thursday after the first sunday in September)
960 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
961 $jour_1sunsept = date("d", $date_1sunsept);
962 $mois_1sunsept = date("m", $date_1sunsept);
963 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
964 $ferie = true;
965 }
966 // Geneva fast in Switzerland
967 }
968 }
969 //print "ferie=".$ferie."\n";
970
971 // If we have to include Friday, Saturday and Sunday
972 if (!$ferie) {
973 if ($includefriday || $includesaturday || $includesunday) {
974 $jour_julien = unixtojd($timestampStart);
975 $jour_semaine = jddayofweek($jour_julien, 0);
976 if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
977 if ($jour_semaine == 5) {
978 $ferie = true;
979 }
980 }
981 if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
982 if ($jour_semaine == 6) {
983 $ferie = true;
984 }
985 }
986 if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
987 if ($jour_semaine == 0) {
988 $ferie = true;
989 }
990 }
991 }
992 }
993 //print "ferie=".$ferie."\n";
994
995 // We increase the counter of non working day
996 if ($ferie) {
997 $nbFerie++;
998 }
999
1000 // Increase number of days (on go up into loop)
1001 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
1002 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
1003
1004 $i++;
1005 }
1006
1007 //print "nbFerie=".$nbFerie."\n";
1008 return $nbFerie;
1009}
1010
1021function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1022{
1023 if ($timestampStart < $timestampEnd) {
1024 if ($lastday == 1) {
1025 $bit = 0;
1026 } else {
1027 $bit = 1;
1028 }
1029 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1030 } else {
1031 $nbjours = 0;
1032 }
1033 //print ($timestampEnd - $timestampStart) - $lastday;
1034 return $nbjours;
1035}
1036
1049function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1050{
1051 global $langs, $mysoc;
1052
1053 if (empty($country_code)) {
1054 $country_code = $mysoc->country_code;
1055 }
1056
1057 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1058
1059 // Check parameters
1060 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1061 return 'ErrorBadParameter_num_open_day';
1062 }
1063 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1064 return 'ErrorBadParameter_num_open_day';
1065 }
1066
1067 //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1068 if ($timestampStart < $timestampEnd) {
1069 $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1070
1071 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1072 $nbOpenDay = ($numdays - $numholidays);
1073 if ($inhour == 1 && $nbOpenDay <= 3) {
1074 $nbOpenDay = ($nbOpenDay * 24);
1075 }
1076 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1077 } elseif ($timestampStart == $timestampEnd) {
1078 $numholidays = 0;
1079 if ($lastday) {
1080 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1081 if ($numholidays == 1) {
1082 return 0;
1083 }
1084 }
1085
1086 $nbOpenDay = $lastday;
1087
1088 if ($inhour == 1) {
1089 $nbOpenDay = ($nbOpenDay * 24);
1090 }
1091 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1092 } else {
1093 return $langs->trans("Error");
1094 }
1095}
1096
1097
1098
1107function monthArray($outputlangs, $short = 0)
1108{
1109 $montharray = array(
1110 1 => $outputlangs->trans("Month01"),
1111 2 => $outputlangs->trans("Month02"),
1112 3 => $outputlangs->trans("Month03"),
1113 4 => $outputlangs->trans("Month04"),
1114 5 => $outputlangs->trans("Month05"),
1115 6 => $outputlangs->trans("Month06"),
1116 7 => $outputlangs->trans("Month07"),
1117 8 => $outputlangs->trans("Month08"),
1118 9 => $outputlangs->trans("Month09"),
1119 10 => $outputlangs->trans("Month10"),
1120 11 => $outputlangs->trans("Month11"),
1121 12 => $outputlangs->trans("Month12")
1122 );
1123
1124 if (!empty($short)) {
1125 $montharray = array(
1126 1 => $outputlangs->trans("MonthShort01"),
1127 2 => $outputlangs->trans("MonthShort02"),
1128 3 => $outputlangs->trans("MonthShort03"),
1129 4 => $outputlangs->trans("MonthShort04"),
1130 5 => $outputlangs->trans("MonthShort05"),
1131 6 => $outputlangs->trans("MonthShort06"),
1132 7 => $outputlangs->trans("MonthShort07"),
1133 8 => $outputlangs->trans("MonthShort08"),
1134 9 => $outputlangs->trans("MonthShort09"),
1135 10 => $outputlangs->trans("MonthShort10"),
1136 11 => $outputlangs->trans("MonthShort11"),
1137 12 => $outputlangs->trans("MonthShort12")
1138 );
1139 }
1140
1141 return $montharray;
1142}
1143
1151function getWeekNumbersOfMonth($month, $year)
1152{
1153 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1154 $TWeek = array();
1155 for ($day = 1; $day < $nb_days; $day++) {
1156 $week_number = getWeekNumber($day, $month, $year);
1157 $TWeek[$week_number] = $week_number;
1158 }
1159 return $TWeek;
1160}
1161
1169function getFirstDayOfEachWeek($TWeek, $year)
1170{
1171 $TFirstDayOfWeek = array();
1172 foreach ($TWeek as $weekNb) {
1173 if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1174 $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année
1175 }
1176 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1177 }
1178 return $TFirstDayOfWeek;
1179}
1180
1188function getLastDayOfEachWeek($TWeek, $year)
1189{
1190 $TLastDayOfWeek = array();
1191 foreach ($TWeek as $weekNb) {
1192 $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1193 }
1194 return $TLastDayOfWeek;
1195}
1196
1205function getWeekNumber($day, $month, $year)
1206{
1207 $date = new DateTime($year.'-'.$month.'-'.$day);
1208 $week = $date->format("W");
1209 return $week;
1210}
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:514
dol_get_first_hour($date, $gm='tzserver')
Return GMT time for first hour of a given GMT date (it removes hours, min and second part)
Definition date.lib.php:655
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:499
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:573
dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand=0, $gm=false)
Generate a SQL string to make a filter into a range (for second of date until last second of date).
Definition date.lib.php:378
getServerTimeZoneString()
Return server timezone string.
Definition date.lib.php:75
dol_get_last_hour($date, $gm='tzserver')
Return GMT time for last hour of a given GMT date (it replaces hours, min and second part to 23:59:59...
Definition date.lib.php:641
getLastDayOfEachWeek($TWeek, $year)
Return array of last day of weeks.
getWeekNumbersOfMonth($month, $year)
Return array of week numbers.
getServerTimeZoneInt($refgmtdate='now')
Return server timezone int.
Definition date.lib.php:86
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:670
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:740
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:334
get_tz_array()
Return an array with timezone values.
Definition date.lib.php:36
dol_get_prev_day($day, $month, $year)
Return previous day.
Definition date.lib.php:483
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:595
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:533
getWeekNumber($day, $month, $year)
Return week number.
num_between_day($timestampStart, $timestampEnd, $lastday=0)
Function to return number of days between two dates (date must be UTC date !) Example: 2012-01-01 201...
convertTime2Seconds($iHours=0, $iMinutes=0, $iSeconds=0)
Convert hours and minutes into seconds.
Definition date.lib.php:213
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:242
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:554
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:427
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:614
monthArray($outputlangs, $short=0)
Return array of translated months or selected month.
num_public_holiday($timestampStart, $timestampEnd, $country_code='', $lastday=0, $includesaturday=-1, $includesunday=-1, $includefriday=-1, $includemonday=-1)
Return the number of non working days including Friday, Saturday and Sunday (or not) between 2 dates ...
Definition date.lib.php:764
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.