composer package updates
[openemr.git] / vendor / phpoffice / phpspreadsheet / src / PhpSpreadsheet / Shared / Date.php
blob91c3ee0e2cae295e5d22330968ccff55642e2d4a
1 <?php
3 namespace PhpOffice\PhpSpreadsheet\Shared;
5 use DateTimeInterface;
6 use DateTimeZone;
7 use PhpOffice\PhpSpreadsheet\Calculation\DateTime;
8 use PhpOffice\PhpSpreadsheet\Calculation\Functions;
9 use PhpOffice\PhpSpreadsheet\Cell\Cell;
10 use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
12 class Date
14 /** constants */
15 const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0
16 const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0
18 /**
19 * Names of the months of the year, indexed by shortname
20 * Planned usage for locale settings.
22 * @var string[]
24 public static $monthNames = [
25 'Jan' => 'January',
26 'Feb' => 'February',
27 'Mar' => 'March',
28 'Apr' => 'April',
29 'May' => 'May',
30 'Jun' => 'June',
31 'Jul' => 'July',
32 'Aug' => 'August',
33 'Sep' => 'September',
34 'Oct' => 'October',
35 'Nov' => 'November',
36 'Dec' => 'December',
39 /**
40 * @var string[]
42 public static $numberSuffixes = [
43 'st',
44 'nd',
45 'rd',
46 'th',
49 /**
50 * Base calendar year to use for calculations
51 * Value is either CALENDAR_WINDOWS_1900 (1900) or CALENDAR_MAC_1904 (1904).
53 * @var int
55 protected static $excelCalendar = self::CALENDAR_WINDOWS_1900;
57 /**
58 * Default timezone to use for DateTime objects.
60 * @var null|\DateTimeZone
62 protected static $defaultTimeZone;
64 /**
65 * Set the Excel calendar (Windows 1900 or Mac 1904).
67 * @param int $baseDate Excel base date (1900 or 1904)
69 * @return bool Success or failure
71 public static function setExcelCalendar($baseDate)
73 if (($baseDate == self::CALENDAR_WINDOWS_1900) ||
74 ($baseDate == self::CALENDAR_MAC_1904)) {
75 self::$excelCalendar = $baseDate;
77 return true;
80 return false;
83 /**
84 * Return the Excel calendar (Windows 1900 or Mac 1904).
86 * @return int Excel base date (1900 or 1904)
88 public static function getExcelCalendar()
90 return self::$excelCalendar;
93 /**
94 * Set the Default timezone to use for dates.
96 * @param DateTimeZone|string $timeZone The timezone to set for all Excel datetimestamp to PHP DateTime Object conversions
98 * @throws \Exception
100 * @return bool Success or failure
101 * @return bool Success or failure
103 public static function setDefaultTimezone($timeZone)
105 if ($timeZone = self::validateTimeZone($timeZone)) {
106 self::$defaultTimeZone = $timeZone;
108 return true;
111 return false;
115 * Return the Default timezone being used for dates.
117 * @return DateTimeZone The timezone being used as default for Excel timestamp to PHP DateTime object
119 public static function getDefaultTimezone()
121 if (self::$defaultTimeZone === null) {
122 self::$defaultTimeZone = new DateTimeZone('UTC');
125 return self::$defaultTimeZone;
129 * Validate a timezone.
131 * @param DateTimeZone|string $timeZone The timezone to validate, either as a timezone string or object
133 * @throws \Exception
135 * @return DateTimeZone The timezone as a timezone object
136 * @return DateTimeZone The timezone as a timezone object
138 protected static function validateTimeZone($timeZone)
140 if (is_object($timeZone) && $timeZone instanceof DateTimeZone) {
141 return $timeZone;
142 } elseif (is_string($timeZone)) {
143 return new DateTimeZone($timeZone);
146 throw new \Exception('Invalid timezone');
150 * Convert a MS serialized datetime value from Excel to a PHP Date/Time object.
152 * @param float|int $excelTimestamp MS Excel serialized date/time value
153 * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
154 * if you don't want to treat it as a UTC value
155 * Use the default (UST) unless you absolutely need a conversion
157 * @throws \Exception
159 * @return \DateTime PHP date/time object
161 public static function excelToDateTimeObject($excelTimestamp, $timeZone = null)
163 $timeZone = ($timeZone === null) ? self::getDefaultTimezone() : self::validateTimeZone($timeZone);
164 if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_EXCEL) {
165 if ($excelTimestamp < 1.0) {
166 // Unix timestamp base date
167 $baseDate = new \DateTime('1970-01-01', $timeZone);
168 } else {
169 // MS Excel calendar base dates
170 if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
171 // Allow adjustment for 1900 Leap Year in MS Excel
172 $baseDate = ($excelTimestamp < 60) ? new \DateTime('1899-12-31', $timeZone) : new \DateTime('1899-12-30', $timeZone);
173 } else {
174 $baseDate = new \DateTime('1904-01-01', $timeZone);
177 } else {
178 $baseDate = new \DateTime('1899-12-30', $timeZone);
181 $days = floor($excelTimestamp);
182 $partDay = $excelTimestamp - $days;
183 $hours = floor($partDay * 24);
184 $partDay = $partDay * 24 - $hours;
185 $minutes = floor($partDay * 60);
186 $partDay = $partDay * 60 - $minutes;
187 $seconds = round($partDay * 60);
189 if ($days >= 0) {
190 $days = '+' . $days;
192 $interval = $days . ' days';
194 return $baseDate->modify($interval)
195 ->setTime($hours, $minutes, $seconds);
199 * Convert a MS serialized datetime value from Excel to a unix timestamp.
201 * @param float|int $excelTimestamp MS Excel serialized date/time value
202 * @param null|DateTimeZone|string $timeZone The timezone to assume for the Excel timestamp,
203 * if you don't want to treat it as a UTC value
204 * Use the default (UST) unless you absolutely need a conversion
206 * @throws \Exception
208 * @return int Unix timetamp for this date/time
210 public static function excelToTimestamp($excelTimestamp, $timeZone = null)
212 return (int) self::excelToDateTimeObject($excelTimestamp, $timeZone)
213 ->format('U');
217 * Convert a date from PHP to an MS Excel serialized date/time value.
219 * @param mixed $dateValue Unix Timestamp or PHP DateTime object or a string
221 * @return bool|float Excel date/time value
222 * or boolean FALSE on failure
224 public static function PHPToExcel($dateValue)
226 if ((is_object($dateValue)) && ($dateValue instanceof DateTimeInterface)) {
227 return self::dateTimeToExcel($dateValue);
228 } elseif (is_numeric($dateValue)) {
229 return self::timestampToExcel($dateValue);
230 } elseif (is_string($dateValue)) {
231 return self::stringToExcel($dateValue);
234 return false;
238 * Convert a PHP DateTime object to an MS Excel serialized date/time value.
240 * @param DateTimeInterface $dateValue PHP DateTime object
242 * @return float MS Excel serialized date/time value
244 public static function dateTimeToExcel(DateTimeInterface $dateValue)
246 return self::formattedPHPToExcel(
247 $dateValue->format('Y'),
248 $dateValue->format('m'),
249 $dateValue->format('d'),
250 $dateValue->format('H'),
251 $dateValue->format('i'),
252 $dateValue->format('s')
257 * Convert a Unix timestamp to an MS Excel serialized date/time value.
259 * @param int $dateValue Unix Timestamp
261 * @return float MS Excel serialized date/time value
263 public static function timestampToExcel($dateValue)
265 if (!is_numeric($dateValue)) {
266 return false;
269 return self::dateTimeToExcel(new \DateTime('@' . $dateValue));
273 * formattedPHPToExcel.
275 * @param int $year
276 * @param int $month
277 * @param int $day
278 * @param int $hours
279 * @param int $minutes
280 * @param int $seconds
282 * @return float Excel date/time value
284 public static function formattedPHPToExcel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0)
286 if (self::$excelCalendar == self::CALENDAR_WINDOWS_1900) {
288 // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel
289 // This affects every date following 28th February 1900
291 $excel1900isLeapYear = true;
292 if (($year == 1900) && ($month <= 2)) {
293 $excel1900isLeapYear = false;
295 $myexcelBaseDate = 2415020;
296 } else {
297 $myexcelBaseDate = 2416481;
298 $excel1900isLeapYear = false;
301 // Julian base date Adjustment
302 if ($month > 2) {
303 $month -= 3;
304 } else {
305 $month += 9;
306 --$year;
309 // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
310 $century = substr($year, 0, 2);
311 $decade = substr($year, 2, 2);
312 $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear;
314 $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
316 return (float) $excelDate + $excelTime;
320 * Is a given cell a date/time?
322 * @param Cell $pCell
324 * @return bool
326 public static function isDateTime(Cell $pCell)
328 return self::isDateTimeFormat(
329 $pCell->getWorksheet()->getStyle(
330 $pCell->getCoordinate()
331 )->getNumberFormat()
336 * Is a given number format a date/time?
338 * @param NumberFormat $pFormat
340 * @return bool
342 public static function isDateTimeFormat(NumberFormat $pFormat)
344 return self::isDateTimeFormatCode($pFormat->getFormatCode());
347 private static $possibleDateFormatCharacters = 'eymdHs';
350 * Is a given number format code a date/time?
352 * @param string $pFormatCode
354 * @return bool
356 public static function isDateTimeFormatCode($pFormatCode)
358 if (strtolower($pFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
359 // "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check)
360 return false;
362 if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) {
363 // Scientific format
364 return false;
367 // Switch on formatcode
368 switch ($pFormatCode) {
369 // Explicitly defined date formats
370 case NumberFormat::FORMAT_DATE_YYYYMMDD:
371 case NumberFormat::FORMAT_DATE_YYYYMMDD2:
372 case NumberFormat::FORMAT_DATE_DDMMYYYY:
373 case NumberFormat::FORMAT_DATE_DMYSLASH:
374 case NumberFormat::FORMAT_DATE_DMYMINUS:
375 case NumberFormat::FORMAT_DATE_DMMINUS:
376 case NumberFormat::FORMAT_DATE_MYMINUS:
377 case NumberFormat::FORMAT_DATE_DATETIME:
378 case NumberFormat::FORMAT_DATE_TIME1:
379 case NumberFormat::FORMAT_DATE_TIME2:
380 case NumberFormat::FORMAT_DATE_TIME3:
381 case NumberFormat::FORMAT_DATE_TIME4:
382 case NumberFormat::FORMAT_DATE_TIME5:
383 case NumberFormat::FORMAT_DATE_TIME6:
384 case NumberFormat::FORMAT_DATE_TIME7:
385 case NumberFormat::FORMAT_DATE_TIME8:
386 case NumberFormat::FORMAT_DATE_YYYYMMDDSLASH:
387 case NumberFormat::FORMAT_DATE_XLSX14:
388 case NumberFormat::FORMAT_DATE_XLSX15:
389 case NumberFormat::FORMAT_DATE_XLSX16:
390 case NumberFormat::FORMAT_DATE_XLSX17:
391 case NumberFormat::FORMAT_DATE_XLSX22:
392 return true;
395 // Typically number, currency or accounting (or occasionally fraction) formats
396 if ((substr($pFormatCode, 0, 1) == '_') || (substr($pFormatCode, 0, 2) == '0 ')) {
397 return false;
399 // Try checking for any of the date formatting characters that don't appear within square braces
400 if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $pFormatCode)) {
401 // We might also have a format mask containing quoted strings...
402 // we don't want to test for any of our characters within the quoted blocks
403 if (strpos($pFormatCode, '"') !== false) {
404 $segMatcher = false;
405 foreach (explode('"', $pFormatCode) as $subVal) {
406 // Only test in alternate array entries (the non-quoted blocks)
407 if (($segMatcher = !$segMatcher) &&
408 (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $subVal))) {
409 return true;
413 return false;
416 return true;
419 // No date...
420 return false;
424 * Convert a date/time string to Excel time.
426 * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10'
428 * @return false|float Excel date/time serial value
430 public static function stringToExcel($dateValue)
432 if (strlen($dateValue) < 2) {
433 return false;
435 if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue)) {
436 return false;
439 $dateValueNew = DateTime::DATEVALUE($dateValue);
441 if ($dateValueNew === Functions::VALUE()) {
442 return false;
445 if (strpos($dateValue, ':') !== false) {
446 $timeValue = DateTime::TIMEVALUE($dateValue);
447 if ($timeValue === Functions::VALUE()) {
448 return false;
450 $dateValueNew += $timeValue;
453 return $dateValueNew;
457 * Converts a month name (either a long or a short name) to a month number.
459 * @param string $month Month name or abbreviation
461 * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
463 public static function monthStringToNumber($month)
465 $monthIndex = 1;
466 foreach (self::$monthNames as $shortMonthName => $longMonthName) {
467 if (($month === $longMonthName) || ($month === $shortMonthName)) {
468 return $monthIndex;
470 ++$monthIndex;
473 return $month;
477 * Strips an ordinal from a numeric value.
479 * @param string $day Day number with an ordinal
481 * @return int|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric
483 public static function dayStringToNumber($day)
485 $strippedDayValue = (str_replace(self::$numberSuffixes, '', $day));
486 if (is_numeric($strippedDayValue)) {
487 return (int) $strippedDayValue;
490 return $day;