dolibarr 19.0.3
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('', '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 global $conf;
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') {
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 = dol_print_date($time, '%Y');
178 $timemonth = dol_print_date($time, '%m');
179 $timetotalmonths = (($timeyear * 12) + $timemonth);
180
181 $monthsexpected = ($timetotalmonths + $duration_value);
182
183 $newtime = $date->getTimestamp();
184
185 $newtimeyear = dol_print_date($newtime, '%Y');
186 $newtimemonth = dol_print_date($newtime, '%m');
187 $newtimetotalmonths = (($newtimeyear * 12) + $newtimemonth);
188
189 if ($monthsexpected < $newtimetotalmonths) {
190 $newtimehours = dol_print_date($newtime, '%H');
191 $newtimemins = dol_print_date($newtime, '%M');
192 $newtimesecs = 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') {
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
376function dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand = 0, $gm = false)
377{
378 global $db;
379 $sqldate = '';
380
381 $day_date = intval($day_date);
382 $month_date = intval($month_date);
383 $year_date = intval($year_date);
384
385 if ($month_date > 0) {
386 if ($month_date > 12) { // protection for bad value of month
387 return " AND 1 = 2";
388 }
389 if ($year_date > 0 && empty($day_date)) {
390 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, $month_date, $gm));
391 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, $month_date, $gm))."'";
392 } elseif ($year_date > 0 && !empty($day_date)) {
393 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month_date, $day_date, $year_date, $gm));
394 $sqldate .= "' AND '".$db->idate(dol_mktime(23, 59, 59, $month_date, $day_date, $year_date, $gm))."'";
395 } else {
396 // This case is not reliable on TZ, but we should not need it.
397 $sqldate .= ($excludefirstand ? "" : " AND ")." date_format( ".$datefield.", '%c') = '".$db->escape($month_date)."'";
398 }
399 } elseif ($year_date > 0) {
400 $sqldate .= ($excludefirstand ? "" : " AND ").$datefield." BETWEEN '".$db->idate(dol_get_first_day($year_date, 1, $gm));
401 $sqldate .= "' AND '".$db->idate(dol_get_last_day($year_date, 12, $gm))."'";
402 }
403 return $sqldate;
404}
405
425function dol_stringtotime($string, $gm = 1)
426{
427 $reg = array();
428 // Convert date with format DD/MM/YYY HH:MM:SS. This part of code should not be used.
429 if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $string, $reg)) {
430 dol_syslog("dol_stringtotime call to function with deprecated parameter format", LOG_WARNING);
431 // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
432 // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
433 $sday = $reg[1];
434 $smonth = $reg[2];
435 $syear = $reg[3];
436 $shour = $reg[4];
437 $smin = $reg[5];
438 $ssec = $reg[6];
439 if ($syear < 50) {
440 $syear += 1900;
441 }
442 if ($syear >= 50 && $syear < 100) {
443 $syear += 2000;
444 }
445 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
446 } 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)
447 || 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
448 || 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
449 ) {
450 $syear = $reg[1];
451 $smonth = $reg[2];
452 $sday = $reg[3];
453 $shour = $reg[4];
454 $smin = $reg[5];
455 $ssec = $reg[6];
456 $string = sprintf("%04d%02d%02d%02d%02d%02d", $syear, $smonth, $sday, $shour, $smin, $ssec);
457 }
458
459 $string = preg_replace('/([^0-9])/i', '', $string);
460 $tmp = $string.'000000';
461 // Clean $gm
462 if ($gm === 1) {
463 $gm = 'gmt';
464 } elseif (empty($gm) || $gm === 'tzserver') {
465 $gm = 'tzserver';
466 }
467
468 $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);
469 return $date;
470}
471
472
481function dol_get_prev_day($day, $month, $year)
482{
483 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
484 $time -= 24 * 60 * 60;
485 $tmparray = dol_getdate($time, true);
486 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
487}
488
497function dol_get_next_day($day, $month, $year)
498{
499 $time = dol_mktime(12, 0, 0, $month, $day, $year, 1, 0);
500 $time += 24 * 60 * 60;
501 $tmparray = dol_getdate($time, true);
502 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
503}
504
512function dol_get_prev_month($month, $year)
513{
514 if ($month == 1) {
515 $prev_month = 12;
516 $prev_year = $year - 1;
517 } else {
518 $prev_month = $month - 1;
519 $prev_year = $year;
520 }
521 return array('year' => $prev_year, 'month' => $prev_month);
522}
523
531function dol_get_next_month($month, $year)
532{
533 if ($month == 12) {
534 $next_month = 1;
535 $next_year = $year + 1;
536 } else {
537 $next_month = $month + 1;
538 $next_year = $year;
539 }
540 return array('year' => $next_year, 'month' => $next_month);
541}
542
552function dol_get_prev_week($day, $week, $month, $year)
553{
554 $tmparray = dol_get_first_day_week($day, $month, $year);
555
556 $time = dol_mktime(12, 0, 0, $month, $tmparray['first_day'], $year, 1, 0);
557 $time -= 24 * 60 * 60 * 7;
558 $tmparray = dol_getdate($time, true);
559 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
560}
561
571function dol_get_next_week($day, $week, $month, $year)
572{
573 $tmparray = dol_get_first_day_week($day, $month, $year);
574
575 $time = dol_mktime(12, 0, 0, $tmparray['first_month'], $tmparray['first_day'], $tmparray['first_year'], 1, 0);
576 $time += 24 * 60 * 60 * 7;
577 $tmparray = dol_getdate($time, true);
578
579 return array('year' => $tmparray['year'], 'month' => $tmparray['mon'], 'day' => $tmparray['mday']);
580}
581
593function dol_get_first_day($year, $month = 1, $gm = false)
594{
595 if ($year > 9999) {
596 return '';
597 }
598 return dol_mktime(0, 0, 0, $month, 1, $year, $gm);
599}
600
601
612function dol_get_last_day($year, $month = 12, $gm = false)
613{
614 if ($year > 9999) {
615 return '';
616 }
617 if ($month == 12) {
618 $month = 1;
619 $year += 1;
620 } else {
621 $month += 1;
622 }
623
624 // On se deplace au debut du mois suivant, et on retire un jour
625 $datelim = dol_mktime(23, 59, 59, $month, 1, $year, $gm);
626 $datelim -= (3600 * 24);
627
628 return $datelim;
629}
630
639function dol_get_last_hour($date, $gm = 'tzserver')
640{
641 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
642 return dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
643}
644
653function dol_get_first_hour($date, $gm = 'tzserver')
654{
655 $tmparray = dol_getdate($date, false, ($gm == 'gmt' ? 'gmt' : ''));
656 return dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year'], $gm);
657}
658
668function dol_get_first_day_week($day, $month, $year, $gm = false)
669{
670 global $conf;
671
672 //$day=2; $month=2; $year=2015;
673 $date = dol_mktime(0, 0, 0, $month, $day, $year, $gm);
674
675 //Checking conf of start week
676 $start_week = (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1);
677
678 $tmparray = dol_getdate($date, true); // detail of current day
679
680 //Calculate days = offset from current day
681 $days = $start_week - $tmparray['wday'];
682 if ($days >= 1) {
683 $days = 7 - $days;
684 }
685 $days = abs($days);
686 $seconds = $days * 24 * 60 * 60;
687 //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'<br>';
688
689 //Get first day of week
690 $tmpdaytms = date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters
691 $tmpday = date("d", $tmpdaytms);
692
693 //Check first day of week is in same month than current day or not
694 if ($tmpday > $day) {
695 $prev_month = $month - 1;
696 $prev_year = $year;
697
698 if ($prev_month == 0) {
699 $prev_month = 12;
700 $prev_year = $year - 1;
701 }
702 } else {
703 $prev_month = $month;
704 $prev_year = $year;
705 }
706 $tmpmonth = $prev_month;
707 $tmpyear = $prev_year;
708
709 //Get first day of next week
710 $tmptime = dol_mktime(12, 0, 0, $month, $tmpday, $year, 1, 0);
711 $tmptime -= 24 * 60 * 60 * 7;
712 $tmparray = dol_getdate($tmptime, true);
713 $prev_day = $tmparray['mday'];
714
715 //Check prev day of week is in same month than first day or not
716 if ($prev_day > $tmpday) {
717 $prev_month = $month - 1;
718 $prev_year = $year;
719
720 if ($prev_month == 0) {
721 $prev_month = 12;
722 $prev_year = $year - 1;
723 }
724 }
725
726 $week = date("W", dol_mktime(0, 0, 0, $tmpmonth, $tmpday, $tmpyear, $gm));
727
728 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);
729}
730
738function getGMTEasterDatetime($year)
739{
740 $base = new DateTime("$year-03-21", new DateTimeZone("UTC"));
741 $days = easter_days($year); // Return number of days between 21 march and easter day.
742 $tmp = $base->add(new DateInterval("P{$days}D"));
743 return $tmp->getTimestamp();
744}
745
762function num_public_holiday($timestampStart, $timestampEnd, $country_code = '', $lastday = 0, $includesaturday = -1, $includesunday = -1, $includefriday = -1, $includemonday = -1)
763{
764 global $db, $conf, $mysoc;
765
766 $nbFerie = 0;
767
768 // Check to ensure we use correct parameters
769 if (($timestampEnd - $timestampStart) % 86400 != 0) {
770 return 'Error Dates must use same hours and must be GMT dates';
771 }
772
773 if (empty($country_code)) {
774 $country_code = $mysoc->country_code;
775 }
776 if ($includemonday < 0) {
777 $includemonday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_MONDAY : 0);
778 }
779 if ($includefriday < 0) {
780 $includefriday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_FRIDAY : 0);
781 }
782 if ($includesaturday < 0) {
783 $includesaturday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY : 1);
784 }
785 if ($includesunday < 0) {
786 $includesunday = (isset($conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY) ? $conf->global->MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY : 1);
787 }
788
789 $country_id = dol_getIdFromCode($db, $country_code, 'c_country', 'code', 'rowid');
790
791 $i = 0;
792 while ((($lastday == 0 && $timestampStart < $timestampEnd) || ($lastday && $timestampStart <= $timestampEnd))
793 && ($i < 50000)) { // Loop end when equals (Test on i is a security loop to avoid infinite loop)
794 $ferie = false;
795 $specialdayrule = array();
796
797 $jour = gmdate("d", $timestampStart);
798 $mois = gmdate("m", $timestampStart);
799 $annee = gmdate("Y", $timestampStart);
800
801 //print "jour=".$jour." month=".$mois." year=".$annee." includesaturday=".$includesaturday." includesunday=".$includesunday."\n";
802
803 // Loop on public holiday defined into hrm_public_holiday for the day, month and year analyzed
804 // TODO Execute this request first and store results into an array, then reuse this array.
805 $sql = "SELECT code, entity, fk_country, dayrule, year, month, day, active";
806 $sql .= " FROM ".MAIN_DB_PREFIX."c_hrm_public_holiday";
807 $sql .= " WHERE active = 1 and fk_country IN (0".($country_id > 0 ? ", ".$country_id : 0).")";
808 $sql .= " AND entity IN (0," .getEntity('holiday') .")";
809
810 $resql = $db->query($sql);
811 if ($resql) {
812 $num_rows = $db->num_rows($resql);
813 $i = 0;
814 while ($i < $num_rows) {
815 $obj = $db->fetch_object($resql);
816
817 if (!empty($obj->dayrule) && $obj->dayrule != 'date') { // For example 'easter', '...'
818 $specialdayrule[$obj->dayrule] = $obj->dayrule;
819 } else {
820 $match = 1;
821 if (!empty($obj->year) && $obj->year != $annee) {
822 $match = 0;
823 }
824 if ($obj->month != $mois) {
825 $match = 0;
826 }
827 if ($obj->day != $jour) {
828 $match = 0;
829 }
830
831 if ($match) {
832 $ferie = true;
833 }
834 }
835
836 $i++;
837 }
838 } else {
839 dol_syslog($db->lasterror(), LOG_ERR);
840 return 'Error sql '.$db->lasterror();
841 }
842 //var_dump($specialdayrule)."\n";
843 //print "ferie=".$ferie."\n";
844
845 if (!$ferie) {
846 // Special dayrules
847 if (in_array('easter', $specialdayrule)) {
848 // Calculation for easter date
849 $date_paques = getGMTEasterDatetime($annee);
850 $jour_paques = gmdate("d", $date_paques);
851 $mois_paques = gmdate("m", $date_paques);
852 if ($jour_paques == $jour && $mois_paques == $mois) {
853 $ferie = true;
854 }
855 // Easter (sunday)
856 }
857
858 if (in_array('eastermonday', $specialdayrule)) {
859 // Calculation for the monday of easter date
860 $date_paques = getGMTEasterDatetime($annee);
861 //print 'PPP'.$date_paques.' '.dol_print_date($date_paques, 'dayhour', 'gmt')." ";
862 $date_lundi_paques = $date_paques + (3600 * 24);
863 $jour_lundi_paques = gmdate("d", $date_lundi_paques);
864 $mois_lundi_paques = gmdate("m", $date_lundi_paques);
865 if ($jour_lundi_paques == $jour && $mois_lundi_paques == $mois) {
866 $ferie = true;
867 }
868 // Easter (monday)
869 //print 'annee='.$annee.' $jour='.$jour.' $mois='.$mois.' $jour_lundi_paques='.$jour_lundi_paques.' $mois_lundi_paques='.$mois_lundi_paques."\n";
870 }
871
872 //Good Friday
873 if (in_array('goodfriday', $specialdayrule)) {
874 // Pulls the date of Easter
875 $easter = getGMTEasterDatetime($annee);
876
877 // Calculates the date of Good Friday based on Easter
878 $date_good_friday = $easter - (2 * 3600 * 24);
879 $dom_good_friday = gmdate("d", $date_good_friday);
880 $month_good_friday = gmdate("m", $date_good_friday);
881
882 if ($dom_good_friday == $jour && $month_good_friday == $mois) {
883 $ferie = true;
884 }
885 }
886
887 if (in_array('ascension', $specialdayrule)) {
888 // Calcul du jour de l'ascension (39 days after easter day)
889 $date_paques = getGMTEasterDatetime($annee);
890 $date_ascension = $date_paques + (3600 * 24 * 39);
891 $jour_ascension = gmdate("d", $date_ascension);
892 $mois_ascension = gmdate("m", $date_ascension);
893 if ($jour_ascension == $jour && $mois_ascension == $mois) {
894 $ferie = true;
895 }
896 // Ascension (thursday)
897 }
898
899 if (in_array('pentecost', $specialdayrule)) {
900 // Calculation of "Pentecote" (49 days after easter day)
901 $date_paques = getGMTEasterDatetime($annee);
902 $date_pentecote = $date_paques + (3600 * 24 * 49);
903 $jour_pentecote = gmdate("d", $date_pentecote);
904 $mois_pentecote = gmdate("m", $date_pentecote);
905 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
906 $ferie = true;
907 }
908 // "Pentecote" (sunday)
909 }
910 if (in_array('pentecotemonday', $specialdayrule)) {
911 // Calculation of "Pentecote" (49 days after easter day)
912 $date_paques = getGMTEasterDatetime($annee);
913 $date_pentecote = $date_paques + (3600 * 24 * 50);
914 $jour_pentecote = gmdate("d", $date_pentecote);
915 $mois_pentecote = gmdate("m", $date_pentecote);
916 if ($jour_pentecote == $jour && $mois_pentecote == $mois) {
917 $ferie = true;
918 }
919 // "Pentecote" (monday)
920 }
921
922 if (in_array('viernessanto', $specialdayrule)) {
923 // Viernes Santo
924 $date_paques = getGMTEasterDatetime($annee);
925 $date_viernes = $date_paques - (3600 * 24 * 2);
926 $jour_viernes = gmdate("d", $date_viernes);
927 $mois_viernes = gmdate("m", $date_viernes);
928 if ($jour_viernes == $jour && $mois_viernes == $mois) {
929 $ferie = true;
930 }
931 //Viernes Santo
932 }
933
934 if (in_array('fronleichnam', $specialdayrule)) {
935 // Fronleichnam (60 days after easter sunday)
936 $date_paques = getGMTEasterDatetime($annee);
937 $date_fronleichnam = $date_paques + (3600 * 24 * 60);
938 $jour_fronleichnam = gmdate("d", $date_fronleichnam);
939 $mois_fronleichnam = gmdate("m", $date_fronleichnam);
940 if ($jour_fronleichnam == $jour && $mois_fronleichnam == $mois) {
941 $ferie = true;
942 }
943 // Fronleichnam
944 }
945
946 if (in_array('genevafast', $specialdayrule)) {
947 // Geneva fast in Switzerland (Thursday after the first sunday in September)
948 $date_1sunsept = strtotime('next thursday', strtotime('next sunday', mktime(0, 0, 0, 9, 1, $annee)));
949 $jour_1sunsept = date("d", $date_1sunsept);
950 $mois_1sunsept = date("m", $date_1sunsept);
951 if ($jour_1sunsept == $jour && $mois_1sunsept == $mois) {
952 $ferie=true;
953 }
954 // Geneva fast in Switzerland
955 }
956 }
957 //print "ferie=".$ferie."\n";
958
959 // If we have to include Friday, Saturday and Sunday
960 if (!$ferie) {
961 if ($includefriday || $includesaturday || $includesunday) {
962 $jour_julien = unixtojd($timestampStart);
963 $jour_semaine = jddayofweek($jour_julien, 0);
964 if ($includefriday) { //Friday (5), Saturday (6) and Sunday (0)
965 if ($jour_semaine == 5) {
966 $ferie = true;
967 }
968 }
969 if ($includesaturday) { //Friday (5), Saturday (6) and Sunday (0)
970 if ($jour_semaine == 6) {
971 $ferie = true;
972 }
973 }
974 if ($includesunday) { //Friday (5), Saturday (6) and Sunday (0)
975 if ($jour_semaine == 0) {
976 $ferie = true;
977 }
978 }
979 }
980 }
981 //print "ferie=".$ferie."\n";
982
983 // We increase the counter of non working day
984 if ($ferie) {
985 $nbFerie++;
986 }
987
988 // Increase number of days (on go up into loop)
989 $timestampStart = dol_time_plus_duree($timestampStart, 1, 'd');
990 //var_dump($jour.' '.$mois.' '.$annee.' '.$timestampStart);
991
992 $i++;
993 }
994
995 //print "nbFerie=".$nbFerie."\n";
996 return $nbFerie;
997}
998
1009function num_between_day($timestampStart, $timestampEnd, $lastday = 0)
1010{
1011 if ($timestampStart < $timestampEnd) {
1012 if ($lastday == 1) {
1013 $bit = 0;
1014 } else {
1015 $bit = 1;
1016 }
1017 $nbjours = (int) floor(($timestampEnd - $timestampStart) / (60 * 60 * 24)) + 1 - $bit;
1018 }
1019 //print ($timestampEnd - $timestampStart) - $lastday;
1020 return $nbjours;
1021}
1022
1035function num_open_day($timestampStart, $timestampEnd, $inhour = 0, $lastday = 0, $halfday = 0, $country_code = '')
1036{
1037 global $langs, $mysoc;
1038
1039 if (empty($country_code)) {
1040 $country_code = $mysoc->country_code;
1041 }
1042
1043 dol_syslog('num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday.' country_code='.$country_code);
1044
1045 // Check parameters
1046 if (!is_int($timestampStart) && !is_float($timestampStart)) {
1047 return 'ErrorBadParameter_num_open_day';
1048 }
1049 if (!is_int($timestampEnd) && !is_float($timestampEnd)) {
1050 return 'ErrorBadParameter_num_open_day';
1051 }
1052
1053 //print 'num_open_day timestampStart='.$timestampStart.' timestampEnd='.$timestampEnd.' bit='.$lastday;
1054 if ($timestampStart < $timestampEnd) {
1055 $numdays = num_between_day($timestampStart, $timestampEnd, $lastday);
1056
1057 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1058 $nbOpenDay = ($numdays - $numholidays);
1059 if ($inhour == 1 && $nbOpenDay <= 3) {
1060 $nbOpenDay = ($nbOpenDay * 24);
1061 }
1062 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1063 } elseif ($timestampStart == $timestampEnd) {
1064 $numholidays = 0;
1065 if ($lastday) {
1066 $numholidays = num_public_holiday($timestampStart, $timestampEnd, $country_code, $lastday);
1067 if ($numholidays == 1) {
1068 return 0;
1069 }
1070 }
1071
1072 $nbOpenDay = $lastday;
1073
1074 if ($inhour == 1) {
1075 $nbOpenDay = ($nbOpenDay * 24);
1076 }
1077 return $nbOpenDay - (($inhour == 1 ? 12 : 0.5) * abs($halfday));
1078 } else {
1079 return $langs->trans("Error");
1080 }
1081}
1082
1083
1084
1093function monthArray($outputlangs, $short = 0)
1094{
1095 $montharray = array(
1096 1 => $outputlangs->trans("Month01"),
1097 2 => $outputlangs->trans("Month02"),
1098 3 => $outputlangs->trans("Month03"),
1099 4 => $outputlangs->trans("Month04"),
1100 5 => $outputlangs->trans("Month05"),
1101 6 => $outputlangs->trans("Month06"),
1102 7 => $outputlangs->trans("Month07"),
1103 8 => $outputlangs->trans("Month08"),
1104 9 => $outputlangs->trans("Month09"),
1105 10 => $outputlangs->trans("Month10"),
1106 11 => $outputlangs->trans("Month11"),
1107 12 => $outputlangs->trans("Month12")
1108 );
1109
1110 if (!empty($short)) {
1111 $montharray = array(
1112 1 => $outputlangs->trans("MonthShort01"),
1113 2 => $outputlangs->trans("MonthShort02"),
1114 3 => $outputlangs->trans("MonthShort03"),
1115 4 => $outputlangs->trans("MonthShort04"),
1116 5 => $outputlangs->trans("MonthShort05"),
1117 6 => $outputlangs->trans("MonthShort06"),
1118 7 => $outputlangs->trans("MonthShort07"),
1119 8 => $outputlangs->trans("MonthShort08"),
1120 9 => $outputlangs->trans("MonthShort09"),
1121 10 => $outputlangs->trans("MonthShort10"),
1122 11 => $outputlangs->trans("MonthShort11"),
1123 12 => $outputlangs->trans("MonthShort12")
1124 );
1125 }
1126
1127 return $montharray;
1128}
1136function getWeekNumbersOfMonth($month, $year)
1137{
1138 $nb_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
1139 $TWeek = array();
1140 for ($day = 1; $day < $nb_days; $day++) {
1141 $week_number = getWeekNumber($day, $month, $year);
1142 $TWeek[$week_number] = $week_number;
1143 }
1144 return $TWeek;
1145}
1153function getFirstDayOfEachWeek($TWeek, $year)
1154{
1155 $TFirstDayOfWeek = array();
1156 foreach ($TWeek as $weekNb) {
1157 if (in_array('01', $TWeek) && in_array('52', $TWeek) && $weekNb == '01') {
1158 $year++; //Si on a la 1re semaine et la semaine 52 c'est qu'on change d'année
1159 }
1160 $TFirstDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb));
1161 }
1162 return $TFirstDayOfWeek;
1163}
1171function getLastDayOfEachWeek($TWeek, $year)
1172{
1173 $TLastDayOfWeek = array();
1174 foreach ($TWeek as $weekNb) {
1175 $TLastDayOfWeek[$weekNb] = date('d', strtotime($year.'W'.$weekNb.'+6 days'));
1176 }
1177 return $TLastDayOfWeek;
1178}
1187function getWeekNumber($day, $month, $year)
1188{
1189 $date = new DateTime($year.'-'.$month.'-'.$day);
1190 $week = $date->format("W");
1191 return $week;
1192}
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:512
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:653
dol_get_next_day($day, $month, $year)
Return next day.
Definition date.lib.php:497
dol_get_next_week($day, $week, $month, $year)
Return next week.
Definition date.lib.php:571
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:376
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:639
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:668
getGMTEasterDatetime($year)
Return the easter day in GMT time.
Definition date.lib.php:738
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:481
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:593
getFirstDayOfEachWeek($TWeek, $year)
Return array of first day of weeks.
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:531
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: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:242
dol_get_prev_week($day, $week, $month, $year)
Return previous week.
Definition date.lib.php:552
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:425
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:612
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:762
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
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.