dolibarr 21.0.0-alpha
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/Midway",
40 -10 => "Pacific/Fakaofo",
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/Anguilla",
47 -3 => "America/Araguaina",
48 -2 => "America/Noronha",
49 -1 => "Atlantic/Azores",
50 0 => "Africa/Abidjan",
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/Enderbury"
64 );
65 return $tzarray;
66}
67
68
75{
76 return @date_default_timezone_get();
77}
78
85function getServerTimeZoneInt($refgmtdate = 'now')
86{
87 if (method_exists('DateTimeZone', 'getOffset')) {
88 // Method 1 (include daylight)
89 $gmtnow = dol_now('gmt');
90 $yearref = dol_print_date($gmtnow, '%Y');
91 $monthref = dol_print_date($gmtnow, '%m');
92 $dayref = dol_print_date($gmtnow, '%d');
93 if ($refgmtdate == 'now') {
94 $newrefgmtdate = $yearref.'-'.$monthref.'-'.$dayref;
95 } elseif ($refgmtdate == 'summer') {
96 $newrefgmtdate = $yearref.'-08-01';
97 } else {
98 $newrefgmtdate = $yearref.'-01-01';
99 }
100 $newrefgmtdate .= 'T00:00:00+00:00';
101 $localtz = new DateTimeZone(getServerTimeZoneString());
102 $localdt = new DateTime($newrefgmtdate, $localtz);
103 $tmp = -1 * $localtz->getOffset($localdt);
104 //print $refgmtdate.'='.$tmp;
105 } else {
106 $tmp = 0;
107 dol_print_error(null, 'PHP version must be 5.3+');
108 }
109 $tz = round(($tmp < 0 ? 1 : -1) * abs($tmp / 3600));
110 return $tz;
111}
112
113
124function dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth = 0)
125{
126 if (empty($duration_value)) {
127 return $time;
128 }
129 if ($duration_unit == 's') {
130 return $time + ($duration_value);
131 }
132 if ($duration_unit == 'i') {
133 return $time + (60 * $duration_value);
134 }
135 if ($duration_unit == 'h') {
136 return $time + (3600 * $duration_value);
137 }
138 if ($duration_unit == 'w') {
139 return $time + (3600 * 24 * 7 * $duration_value);
140 }
141
142 $deltastring = 'P';
143
144 if ($duration_value > 0) {
145 $deltastring .= abs($duration_value);
146 $sub = false;
147 }
148 if ($duration_value < 0) {
149 $deltastring .= abs($duration_value);
150 $sub = true;
151 }
152 if ($duration_unit == 'd') {
153 $deltastring .= "D";
154 }
155 if ($duration_unit == 'm') {
156 $deltastring .= "M";
157 }
158 if ($duration_unit == 'y') {
159 $deltastring .= "Y";
160 }
161
162 $date = new DateTime();
163 if (getDolGlobalString('MAIN_DATE_IN_MEMORY_ARE_GMT')) {
164 $date->setTimezone(new DateTimeZone('UTC'));
165 }
166 $date->setTimestamp($time);
167 $interval = new DateInterval($deltastring);
168
169 if ($sub) {
170 $date->sub($interval);
171 } else {
172 $date->add($interval);
173 }
174 //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)
175 if ($ruleforendofmonth == 1 && $duration_unit == 'm') {
176 $timeyear = (int) dol_print_date($time, '%Y');
177 $timemonth = (int) dol_print_date($time, '%m');
178 $timetotalmonths = (($timeyear * 12) + $timemonth);
179
180 $monthsexpected = ($timetotalmonths + $duration_value);
181
182 $newtime = $date->getTimestamp();
183
184 $newtimeyear = (int) dol_print_date($newtime, '%Y');
185 $newtimemonth = (int) dol_print_date($newtime, '%m');
186 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
187
188 if ($monthsexpected < $newtimetotalmonths) {
189 $newtimehours = (int) dol_print_date($newtime, '%H');
190 $newtimemins = (int) dol_print_date($newtime, '%M');
191 $newtimesecs = (int) dol_print_date($newtime, '%S');
192
193 $datelim = dol_mktime($newtimehours, $newtimemins, $newtimesecs, $newtimemonth, 1, $newtimeyear);
194 $datelim -= (3600 * 24);
195
196 $date->setTimestamp($datelim);
197 }
198 }
199 return $date->getTimestamp();
200}
201
202
212function convertTime2Seconds($iHours = 0, $iMinutes = 0, $iSeconds = 0)
213{
214 $iResult = ((int) $iHours * 3600) + ((int) $iMinutes * 60) + (int) $iSeconds;
215 return $iResult;
216}
217
218
241function convertSecondToTime($iSecond, $format = 'all', $lengthOfDay = 86400, $lengthOfWeek = 7)
242{
243 global $langs;
244
245 if (empty($lengthOfDay)) {
246 $lengthOfDay = 86400; // 1 day = 24 hours
247 }
248 if (empty($lengthOfWeek)) {
249 $lengthOfWeek = 7; // 1 week = 7 days
250 }
251 $nbHbyDay = $lengthOfDay / 3600;
252
253 if ($format == 'all' || $format == 'allwithouthour' || $format == 'allhour' || $format == 'allhourmin' || $format == 'allhourminsec') {
254 if ((int) $iSecond === 0) {
255 return '0'; // This is to avoid having 0 return a 12:00 AM for en_US
256 }
257
258 $sTime = '';
259 $sDay = 0;
260 $sWeek = 0;
261
262 if ($iSecond >= $lengthOfDay) {
263 for ($i = $iSecond; $i >= $lengthOfDay; $i -= $lengthOfDay) {
264 $sDay++;
265 $iSecond -= $lengthOfDay;
266 }
267 $dayTranslate = $langs->trans("Day");
268 if ($iSecond >= ($lengthOfDay * 2)) {
269 $dayTranslate = $langs->trans("Days");
270 }
271 }
272
273 if ($lengthOfWeek < 7) {
274 if ($sDay) {
275 if ($sDay >= $lengthOfWeek) {
276 $sWeek = (int) (($sDay - $sDay % $lengthOfWeek) / $lengthOfWeek);
277 $sDay = $sDay % $lengthOfWeek;
278 $weekTranslate = $langs->trans("DurationWeek");
279 if ($sWeek >= 2) {
280 $weekTranslate = $langs->trans("DurationWeeks");
281 }
282 $sTime .= $sWeek.' '.$weekTranslate.' ';
283 }
284 }
285 }
286 if ($sDay > 0) {
287 $dayTranslate = $langs->trans("Day");
288 if ($sDay > 1) {
289 $dayTranslate = $langs->trans("Days");
290 }
291 $sTime .= $sDay.' '.$langs->trans("d").' ';
292 }
293
294 if ($format == 'all') {
295 if ($iSecond || empty($sDay)) {
296 $sTime .= dol_print_date($iSecond, 'hourduration', true);
297 }
298 } elseif ($format == 'allhourminsec') {
299 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60))).':'.sprintf("%02d", ((int) ($iSecond % 60)));
300 } elseif ($format == 'allhourmin') {
301 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600))).':'.sprintf("%02d", ((int) floor(($iSecond % 3600) / 60)));
302 } elseif ($format == 'allhour') {
303 return sprintf("%02d", ($sWeek * $lengthOfWeek * $nbHbyDay + $sDay * $nbHbyDay + (int) floor($iSecond / 3600)));
304 }
305 } elseif ($format == 'hour') { // only hour part
306 $sTime = dol_print_date($iSecond, '%H', true);
307 } elseif ($format == 'fullhour') {
308 if (!empty($iSecond)) {
309 $iSecond = $iSecond / 3600;
310 } else {
311 $iSecond = 0;
312 }
313 $sTime = $iSecond;
314 } elseif ($format == 'min') { // only min part
315 $sTime = dol_print_date($iSecond, '%M', true);
316 } elseif ($format == 'sec') { // only sec part
317 $sTime = dol_print_date($iSecond, '%S', true);
318 } elseif ($format == 'month') { // only month part
319 $sTime = dol_print_date($iSecond, '%m', true);
320 } elseif ($format == 'year') { // only year part
321 $sTime = dol_print_date($iSecond, '%Y', true);
322 }
323 return trim($sTime);
324}
325
326
333function convertDurationtoHour($duration_value, $duration_unit)
334{
335 $result = 0;
336
337 if ($duration_unit == 's') {
338 $result = $duration_value / 3600;
339 }
340 if ($duration_unit == 'i') {
341 $result = $duration_value / 60;
342 }
343 if ($duration_unit == 'h') {
344 $result = $duration_value;
345 }
346 if ($duration_unit == 'd') {
347 $result = $duration_value * 24;
348 }
349 if ($duration_unit == 'w') {
350 $result = $duration_value * 24 * 7;
351 }
352 if ($duration_unit == 'm') {
353 $result = $duration_value * 730.484;
354 }
355 if ($duration_unit == 'y') {
356 $result = $duration_value * 365 * 24;
357 }
358
359 return $result;
360}
361
377function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
378{
379 global $db;
380 $sqldate = '';
381
382 $day_date = intval($day_date);
383 $month_date = intval($month_date);
384 $year_date = intval($year_date);
385
386 if ($month_date > 0) {
387 if ($month_date > 12) { // protection for bad value of month
388 return " AND 1 = 2";
389 }
390 if ($year_date > 0 && empty($day_date)) {
391 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
392 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
393 } elseif ($year_date > 0 && !empty($day_date)) {
394 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
395 $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
396 } else {
397 // This case is not reliable on TZ, but we should not need it.
398 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
399 }
400 } elseif ($year_date > 0) {
401 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
402 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
403 }
404 return $sqldate;
405}
406
426function dol_stringtotime($string, $gm = 1)
427{
428 $reg = array();
429 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
430 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
431 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
432 // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
433 // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
434 $sday = (int) $reg[1];
435 $smonth = (int) $reg[2];
436 $syear = (int) $reg[3];
437 $shour = (int) $reg[4];
438 $smin = (int) $reg[5];
439 $ssec = (int) $reg[6];
440 if ($syear < 50) {
441 $syear += 1900;
442 }
443 if ($syear >= 50 && $syear < 100) {
444 $syear += 2000;
445 }
446 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
447 } 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)
448 || 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
449 || 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
450 ) {
451 $syear = (int) $reg[1];
452 $smonth = (int) $reg[2];
453 $sday = (int) $reg[3];
454 $shour = (int) $reg[4];
455 $smin = (int) $reg[5];
456 $ssec = (int) $reg[6];
457 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
458 }
459
460 $string = preg_replace('/([^0-9])/i', '', $string);
461 $tmp = $string.'000000';
462 // Clean $gm
463 if ($gm === 1) {
464 $gm = 'gmt';
465 } elseif (empty($gm) || $gm === 'tzserver') {
466 $gm = 'tzserver';
467 }
468
469 $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);
470 return $date;
471}
472
473
482function dol_get_prev_day($day, $month, $year)
483{
484 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
485 $time -= 24 * 60 * 60;
486 $tmparray = dol_getdate($time, true);
487 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
488}
489
498function dol_get_next_day($day, $month, $year)
499{
500 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
501 $time += 24 * 60 * 60;
502 $tmparray = dol_getdate($time, true);
503 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
504}
505
513function dol_get_prev_month($month, $year)
514{
515 if ($month == 1) {
516 $prev_month = 12;
517 $prev_year = $year - 1;
518 } else {
519 $prev_month = $month - 1;
520 $prev_year = $year;
521 }
522 return array('year' => $prev_year, 'month' => $prev_month);
523}
524
532function dol_get_next_month($month, $year)
533{
534 if ($month == 12) {
535 $next_month = 1;
536 $next_year = $year + 1;
537 } else {
538 $next_month = $month + 1;
539 $next_year = $year;
540 }
541 return array('year' => $next_year, 'month' => $next_month);
542}
543
553function dol_get_prev_week($day, $week, $month, $year)
554{
555 $tmparray = dol_get_first_day_week($day, $month, $year);
556
557 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
558 $time -= 24 * 60 * 60 * 7;
559 $tmparray = dol_getdate($time, true);
560 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
561}
562
572function dol_get_next_week($day, $week, $month, $year)
573{
574 $tmparray = dol_get_first_day_week($day, $month, $year);
575
576 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
577 $time += 24 * 60 * 60 * 7;
578 $tmparray = dol_getdate($time, true);
579
580 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
581}
582
594function dol_get_first_day($year, $month = 1, $gm = false)
595{
596 if ($year > 9999) {
597 return '';
598 }
599 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
600}
601
602
613function dol_get_last_day($year, $month = 12, $gm = false)
614{
615 if ($year > 9999) {
616 return '';
617 }
618 if ($month == 12) {
619 $month = 1;
620 $year += 1;
621 } else {
622 $month += 1;
623 }
624
625 // On se deplace au debut du mois suivant, et on retire un jour
626 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
627 $datelim -= (3600 * 24);
628
629 return $datelim;
630}
631
640function dol_get_last_hour($date, $gm = 'tzserver')
641{
642 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
643 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
644}
645
654function dol_get_first_hour($date, $gm = 'tzserver')
655{
656 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
657 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
658}
659
669function dol_get_first_day_week($day, $month, $year, $gm = false)
670{
671 global $conf;
672
673 //$day=2; $month=2; $year=2015;
674 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
675
676 //Checking conf of start week
677 $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
678
679 $tmparray = dol_getdate($date, true); // detail of current day
680
681 //Calculate days = offset from current day
682 $days = $start_week - $tmparray['wday'];
683 if ($days >= 1) {
684 $days = 7 - $days;
685 }
686 $days = abs($days);
687 $seconds = $days * 24 * 60 * 60;
688 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
689
690 //Get first day of week
691 $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters
692 $tmpday = idate("d", $tmpdaytms);
693
694 //Check first day of week is in same month than current day or not
695 if ($tmpday > $day) {
696 $prev_month = $month - 1;
697 $prev_year = $year;
698
699 if ($prev_month == 0) {
700 $prev_month = 12;
701 $prev_year = $year - 1;
702 }
703 } else {
704 $prev_month = $month;
705 $prev_year = $year;
706 }
707 $tmpmonth = $prev_month;
708 $tmpyear = $prev_year;
709
710 //Get first day of next week
711 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
712 $tmptime -= 24 * 60 * 60 * 7;
713 $tmparray = dol_getdate($tmptime, true);
714 $prev_day = $tmparray['mday'];
715
716 //Check prev day of week is in same month than first day or not
717 if ($prev_day > $tmpday) {
718 $prev_month = $month - 1;
719 $prev_year = $year;
720
721 if ($prev_month == 0) {
722 $prev_month = 12;
723 $prev_year = $year - 1;
724 }
725 }
726
727 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
728
729 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);
730}
731
739function getGMTEasterDatetime($year)
740{
741 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
742 $days = easter_days($year); // Return number of days between 21 march and easter day.
743 $tmp = $base->add(new DateInterval("P{$days}D"));
744 return $tmp->getTimestamp();
745}
746
763function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
764{
765 global $db, $mysoc;
766
767 $nbFerie = 0;
768
769 // Check to ensure we use correct parameters
770 if (($timestampEnd - $timestampStart) % 86400 != 0) {
771 return 'Error Dates must use same hours and must be GMT dates';
772 }
773
774 if (empty($country_code)) {
775 $country_code = $mysoc->country_code;
776 }
777 if ($includemonday < 0) {
778 $includemonday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY', 0);
779 }
780 if ($includefriday < 0) {
781 $includefriday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY', 0);
782 }
783 if ($includesaturday < 0) {
784 $includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
785 }
786 if ($includesunday < 0) {
787 $includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
788 }
789
790 $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
791
792 $i = 0;
793 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
794 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
795 $ferie = false;
796 $specialdayrule = array();
797
798 $jour = (int) gmdate("d", $timestampStart);
799 $mois = (int) gmdate("m", $timestampStart);
800 $annee = (int) gmdate("Y", $timestampStart);
801
802 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
803
804 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
805 // TODO Execute this request first and store results into an array, then reuse this array.
806 $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
807 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
808 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
809 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
810
811 $resql = $db->query($sql);
812 if ($resql) {
813 $num_rows = $db->num_rows($resql);
814 $i = 0;
815 while ($i < $num_rows) {
816 $obj = $db->fetch_object($resql);
817
818 if (!empty($obj->dayrule) && $obj->dayrule != 'date') { // For example 'easter', '...'
819 $specialdayrule[$obj->dayrule] = $obj->dayrule;
820 } else {
821 $match = 1;
822 if (!empty($obj->year) && $obj->year != $annee) {
823 $match = 0;
824 }
825 if ($obj->month != $mois) {
826 $match = 0;
827 }
828 if ($obj->day != $jour) {
829 $match = 0;
830 }
831
832 if ($match) {
833 $ferie = true;
834 }
835 }
836
837 $i++;
838 }
839 } else {
840 dol_syslog($db->lasterror(), LOG_ERR);
841 return 'Error sql '.$db->lasterror();
842 }
843 //var_dump($specialdayrule)."\n";
844 //print "ferie=".$ferie."\n";
845
846 if (!$ferie) {
847 // Special dayrules
848 if (in_array('easter', $specialdayrule)) {
849 // Calculation for easter date
850 $date_paques = getGMTEasterDatetime($annee);
851 $jour_paques = gmdate("d", $date_paques);
852 $mois_paques = gmdate("m", $date_paques);
853 if ($jour_paques == $jour && $mois_paques == $mois) {
854 $ferie = true;
855 }
856 // Easter (sunday)
857 }
858
859 if (in_array('eastermonday', $specialdayrule)) {
860 // Calculation for the monday of easter date
861 $date_paques = getGMTEasterDatetime($annee);
862 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
863 $date_lundi_paques = $date_paques + (3600 * 24);
864 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
865 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
866 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
867 $ferie = true;
868 }
869 // Easter (monday)
870 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
871 }
872
873 //Good Friday
874 if (in_array('goodfriday', $specialdayrule)) {
875 // Pulls the date of Easter
876 $easter = getGMTEasterDatetime($annee);
877
878 // Calculates the date of Good Friday based on Easter
879 $date_good_friday = $easter - (2 * 3600 * 24);
880 $dom_good_friday = gmdate("d", $date_good_friday);
881 $month_good_friday = gmdate("m", $date_good_friday);
882
883 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
884 $ferie = true;
885 }
886 }
887
888 if (in_array('ascension', $specialdayrule)) {
889 // Calcul du jour de l'ascension (39 days after easter day)
890 $date_paques = getGMTEasterDatetime($annee);
891 $date_ascension = $date_paques + (3600 * 24 * 39);
892 $jour_ascension = gmdate("d", $date_ascension);
893 $mois_ascension = gmdate("m", $date_ascension);
894 if ($jour_ascension == $jour && $mois_ascension == $mois) {
895 $ferie = true;
896 }
897 // Ascension (thursday)
898 }
899
900 if (in_array('pentecost', $specialdayrule)) {
901 // Calculation of "Pentecote" (49 days after easter day)
902 $date_paques = getGMTEasterDatetime($annee);
903 $date_pentecote = $date_paques + (3600 * 24 * 49);
904 $jour_pentecote = gmdate("d", $date_pentecote);
905 $mois_pentecote = gmdate("m", $date_pentecote);
906 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
907 $ferie = true;
908 }
909 // "Pentecote" (sunday)
910 }
911 if (in_array('pentecotemonday', $specialdayrule)) {
912 // Calculation of "Pentecote" (49 days after easter day)
913 $date_paques = getGMTEasterDatetime($annee);
914 $date_pentecote = $date_paques + (3600 * 24 * 50);
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" (monday)
921 }
922
923 if (in_array('viernessanto', $specialdayrule)) {
924 // Viernes Santo
925 $date_paques = getGMTEasterDatetime($annee);
926 $date_viernes = $date_paques - (3600 * 24 * 2);
927 $jour_viernes = gmdate("d", $date_viernes);
928 $mois_viernes = gmdate("m", $date_viernes);
929 if ($jour_viernes == $jour && $mois_viernes == $mois) {
930 $ferie = true;
931 }
932 //Viernes Santo
933 }
934
935 if (in_array('fronleichnam', $specialdayrule)) {
936 // Fronleichnam (60 days after easter sunday)
937 $date_paques = getGMTEasterDatetime($annee);
938 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
939 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
940 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
941 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
942 $ferie = true;
943 }
944 // Fronleichnam
945 }
946
947 if (in_array('genevafast', $specialdayrule)) {
948 // Geneva fast in Switzerland (Thursday after the first sunday in September)
949 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
950 $jour_1sunsept = date("d", $date_1sunsept);
951 $mois_1sunsept = date("m", $date_1sunsept);
952 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
953 $ferie = true;
954 }
955 // Geneva fast in Switzerland
956 }
957 }
958 //print "ferie=".$ferie."\n";
959
960 // If we have to include Friday, Saturday and Sunday
961 if (!$ferie) {
962 if ($includefriday || $includesaturday || $includesunday) {
963 $jour_julien = unixtojd($timestampStart);
964 $jour_semaine = jddayofweek($jour_julien, 0);
965 if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
966 if ($jour_semaine == 5) {
967 $ferie = true;
968 }
969 }
970 if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
971 if ($jour_semaine == 6) {
972 $ferie = true;
973 }
974 }
975 if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
976 if ($jour_semaine == 0) {
977 $ferie = true;
978 }
979 }
980 }
981 }
982 //print "ferie=".$ferie."\n";
983
984 // We increase the counter of non working day
985 if ($ferie) {
986 $nbFerie++;
987 }
988
989 // Increase number of days (on go up into loop)
990 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
991 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
992
993 $i++;
994 }
995
996 //print "nbFerie=".$nbFerie."\n";
997 return $nbFerie;
998}
999
1010function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1011{
1012 if ($timestampStart < $timestampEnd) {
1013 if ($lastday == 1) {
1014 $bit = 0;
1015 } else {
1016 $bit = 1;
1017 }
1018 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1019 } else {
1020 $nbjours = 0;
1021 }
1022 //print ($timestampEnd - $timestampStart) - $lastday;
1023 return $nbjours;
1024}
1025
1038function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1039{
1040 global $langs, $mysoc;
1041
1042 if (empty($country_code)) {
1043 $country_code = $mysoc->country_code;
1044 }
1045
1046 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1047
1048 // Check parameters
1049 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1050 return 'ErrorBadParameter_num_open_day';
1051 }
1052 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1053 return 'ErrorBadParameter_num_open_day';
1054 }
1055
1056 //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1057 if ($timestampStart < $timestampEnd) {
1058 $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1059
1060 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1061 $nbOpenDay = ($numdays - $numholidays);
1062 if ($inhour == 1 && $nbOpenDay <= 3) {
1063 $nbOpenDay = ($nbOpenDay * 24);
1064 }
1065 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1066 } elseif ($timestampStart == $timestampEnd) {
1067 $numholidays = 0;
1068 if ($lastday) {
1069 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1070 if ($numholidays == 1) {
1071 return 0;
1072 }
1073 }
1074
1075 $nbOpenDay = $lastday;
1076
1077 if ($inhour == 1) {
1078 $nbOpenDay = ($nbOpenDay * 24);
1079 }
1080 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1081 } else {
1082 return $langs->trans("Error");
1083 }
1084}
1085
1086
1087
1096function monthArray($outputlangs, $short = 0)
1097{
1098 $montharray = array(
1099 1 => $outputlangs->trans("Month01"),
1100 2 => $outputlangs->trans("Month02"),
1101 3 => $outputlangs->trans("Month03"),
1102 4 => $outputlangs->trans("Month04"),
1103 5 => $outputlangs->trans("Month05"),
1104 6 => $outputlangs->trans("Month06"),
1105 7 => $outputlangs->trans("Month07"),
1106 8 => $outputlangs->trans("Month08"),
1107 9 => $outputlangs->trans("Month09"),
1108 10 => $outputlangs->trans("Month10"),
1109 11 => $outputlangs->trans("Month11"),
1110 12 => $outputlangs->trans("Month12")
1111 );
1112
1113 if (!empty($short)) {
1114 $montharray = array(
1115 1 => $outputlangs->trans("MonthShort01"),
1116 2 => $outputlangs->trans("MonthShort02"),
1117 3 => $outputlangs->trans("MonthShort03"),
1118 4 => $outputlangs->trans("MonthShort04"),
1119 5 => $outputlangs->trans("MonthShort05"),
1120 6 => $outputlangs->trans("MonthShort06"),
1121 7 => $outputlangs->trans("MonthShort07"),
1122 8 => $outputlangs->trans("MonthShort08"),
1123 9 => $outputlangs->trans("MonthShort09"),
1124 10 => $outputlangs->trans("MonthShort10"),
1125 11 => $outputlangs->trans("MonthShort11"),
1126 12 => $outputlangs->trans("MonthShort12")
1127 );
1128 }
1129
1130 return $montharray;
1131}
1132
1140function getWeekNumbersOfMonth($month, $year)
1141{
1142 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1143 $TWeek = array();
1144 for ($day = 1; $day < $nb_days; $day++) {
1145 $week_number = getWeekNumber($day, $month, $year);
1146 $TWeek[$week_number] = $week_number;
1147 }
1148 return $TWeek;
1149}
1150
1158function getFirstDayOfEachWeek($TWeek, $year)
1159{
1160 $TFirstDayOfWeek = array();
1161 foreach ($TWeek as $weekNb) {
1162 if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1163 $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année
1164 }
1165 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1166 }
1167 return $TFirstDayOfWeek;
1168}
1169
1177function getLastDayOfEachWeek($TWeek, $year)
1178{
1179 $TLastDayOfWeek = array();
1180 foreach ($TWeek as $weekNb) {
1181 $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1182 }
1183 return $TLastDayOfWeek;
1184}
1185
1194function getWeekNumber($day, $month, $year)
1195{
1196 $date = new DateTime($year.'-'.$month.'-'.$day);
1197 $week = $date->format("W");
1198 return $week;
1199}
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:513
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:654
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:498
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:572
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:377
getServerTimeZoneString()
Return server timezone string.
Definition date.lib.php:74
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:640
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:85
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:669
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:739
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:333
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:482
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:594
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:532
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:212
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:124
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:241
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:553
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:426
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:613
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:763
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.