All files / datepicker date-time-helper.ts

88.05% Statements 258/293
79.14% Branches 148/187
94.73% Functions 54/57
88.07% Lines 251/285

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794                                                1x                   1x           1x               1x   1x                                 1x 92x 92x   1104x                   1x         117x 117x   117x 819x 819x   117x 117x 117x                   1x 1243x                       1x   1243x 1243x 1243x 1243x 1243x 1243x 1243x 1243x     1x 1464x 1464x       1x                                             1x             12180x                       12180x 12180x 12180x 12180x       1x 41x 41x 41x 41x     1x 1x             1x 51x 4x     47x 47x 47x 1x     46x 46x 46x 46x             46x 46x         46x 46x 46x 46x 46x     46x 110x 35x   35x 1x     109x 109x 18x       28x 94x 94x 94x   5x     5x       89x 26x 63x 26x 37x   23x           14x 5x 9x 5x 4x 3x 1x   1x 1x     1x 1x 1x   1x 1x           23x     23x     1x 68x 68x 68x     68x 68x           1x 115x 115x   115x 110x     5x 5x   1x 1x   1x 1x   1x 1x                   2x 2x 2x         2x   5x 5x   5x     1x 2x 2x 4x     2x     7x           9143x               1x           11x     11x 10x   1x                 1x 54x 54x 54x                   1x 25x 25x 25x                     1x           22x 22x 22x 22x                         1x           19x         19x 11x   8x                 1x     25x               1x 215x 215x 215x 215x                 1x 6x 6x 6x               1x 211x             1x 209x             132x         1x 59663x 6732x   52931x                   1x 5307x 257x   5050x           1x 10731x     10731x                 1x 30503x                 1x 31200x                 1x 31667x               1x   17724x   17724x 17724x                   1x   888x   888x 888x                   1x   1044x   1044x 1044x             1x 1553x 1553x 1553x             1x 67x 67x 67x             1x 4x 4x 4x             1x 390x           1x 386x           1x 65x           1x 138x           1x 84x           1x 3x         1x 13x         1x 18x         1x 13x         1x 83x 68x   15x     15x     15x               1x 239x             1x 239x         915x             1x 59x     59x                 1x 2x     2x       1x 10x     1x      
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import {
  FormatWidth,
  FormStyle,
  getLocaleDateFormat,
  getLocaleDateTimeFormat,
  getLocaleDayPeriods,
  getLocaleId,
  getLocaleTimeFormat,
  TranslationWidth
} from '@angular/common';
 
import { WeekStart } from './si-datepicker.model';
 
export interface DayOfWeek {
  id: string;
  index: number;
  offset: number;
  isWeekend: boolean;
}
 
const WEEK_ISO: DayOfWeek[] = [
  { id: 'monday', index: 1, offset: 0, isWeekend: false },
  { id: 'tuesday', index: 2, offset: 1, isWeekend: false },
  { id: 'wednesday', index: 3, offset: 2, isWeekend: false },
  { id: 'thursday', index: 4, offset: 3, isWeekend: false },
  { id: 'friday', index: 5, offset: 4, isWeekend: false },
  { id: 'saturday', index: 6, offset: 5, isWeekend: true },
  { id: 'sunday', index: 7, offset: 6, isWeekend: true }
];
 
export const WEEK_START_OFFSET = {
  'monday': 0,
  'saturday': 5,
  'sunday': 6
};
 
const UNITS = {
  millisecondsPerDay: 86400000,
  daysPerWeek: 7,
  thursday: 4
};
 
const dayOfWeekMap: {
  [key: string]: DayOfWeek[];
} = {};
 
export const getDaysOfWeek = (weekStart: WeekStart): DayOfWeek[] => {
  weekStart = weekStart ?? 'monday';
  let weekdays: DayOfWeek[] = dayOfWeekMap[weekStart];
  Iif (!weekdays) {
    dayOfWeekMap[weekStart] = weekdays = [];
    const offset = WEEK_START_OFFSET[weekStart];
    for (let i = 0; i < 7; i++) {
      weekdays.push({ ...WEEK_ISO[(i + offset) % 7], offset: i });
    }
  }
  return weekdays;
};
 
/**
 * Get local specific months using DateTimeFormat.
 * @param locale - current locale
 */
export const getLocaleMonthNames = (locale: string): string[] => {
  const format = new Intl.DateTimeFormat(locale, { month: 'long', timeZone: 'UTC' }).format;
  return Array(12)
    .fill(0)
    .map((v, m) => format(new Date(Date.UTC(0, m))));
};
 
/**
 * Get local specific weekdays as string using DateTimeFormat.
 * @param locale - current local
 * @param weekStart - start of the week
 * @param format - display format
 * @returns array of week days.
 */
export const getDayStrings = (
  locale: string,
  weekStart: WeekStart = 'monday',
  format: 'narrow' | 'short' | 'long' = 'short'
): string[] => {
  const dateFormatter = new Intl.DateTimeFormat(locale, { weekday: format, timeZone: 'utc' });
  const days = [];
  // Get local specific day strings from sunday (0) .. saturady (6)
  for (let index = 1; index <= 7; index++) {
    const day = new Date(Date.UTC(2023, 0, index));
    days.push(dateFormatter.format(day));
  }
  const map = { 'sunday': 0, 'monday': 1, 'saturday': 6 };
  const index = map[weekStart];
  return days.slice(index).concat(days.slice(0, index));
};
 
/**
 * Gets the first day in the specified month.
 * Expects the month as a value between 1 and 12.
 * The year is required to handle leap years.
 *
 * @returns The first day of the month as a Date.
 */
export const getFirstDayInMonth = (year: number, month: number): Date =>
  new Date(year, month - 1, 1);
 
/**
 * Gets the week number of the specified date.
 * Week number according to the ISO-8601 standard, weeks starting on Monday.
 * The first week of a year is the week that contains the first Thursday of the year (='First 4-day week').
 * The highest week number in a year is either 52 or 53.
 *
 * @param date -The JavaScript date object.
 * @param weekStart -Name of the first day of the week
 * @returns The number of the Week
 */
export const getWeekOfYear = (date: Date, weekStart: WeekStart): number => {
  // Algorithm rewritten from C# example given at http://en.wikipedia.org/wiki/Talk:ISO_week_date
  const dayOfWeek = getWeekDayOffset(date, weekStart) + 1;
  const nearestThu = new Date(date);
  nearestThu.setDate(date.getDate() + (UNITS.thursday - dayOfWeek)); // get nearest Thursday (-3..+3 days)
  const year = nearestThu.getFullYear();
  const janfirst = getFirstDayInMonth(year, 1);
  const days = Math.floor(((nearestThu as any) - (janfirst as any)) / UNITS.millisecondsPerDay);
  const week = 1 + Math.floor(days / UNITS.daysPerWeek); // Count of Thursdays
  return week;
};
 
export const getWeekDayOffset = (date: Date, weekStart: WeekStart): number => {
  const offset = WEEK_START_OFFSET[weekStart ?? 'monday'];
  return (date.getDay() + 6 - offset) % 7;
};
 
/** returns the date string in format YYYY-MM-DD for given date */
export const getStringforDate = (date: Date): string => {
  let month = '' + (date.getMonth() + 1);
  let day = '' + date.getDate();
  const year = date.getFullYear();
 
  Iif (month.length < 2) {
    month = '0' + month;
  }
  Iif (day.length < 2) {
    day = '0' + day;
  }
  return `${year}-${month}-${day}`;
};
 
/**
 * Creates a new date object on from a date with or without time.
 * @param value - The date from with the year, month and day is taken.
 * @param hours - Optional numeric value of the hours, otherwise 0.
 * @param minutes - Optional numeric value of the minutes, otherwise 0.
 * @param seconds - Optional numeric value of the seconds, otherwise 0.
 * @param milliseconds - Optional numeric value of the milliseconds, otherwise 0.
 * @returns
 */
export const createDate = (
  value: Date,
  hours: number = 0,
  minutes: number = 0,
  seconds: number = 0,
  milliseconds: number = 0
): Date => {
  const newDate = new Date(
    value.getFullYear(),
    value.getMonth(),
    value.getDate(),
    hours,
    minutes,
    seconds,
    milliseconds
  );
  // Seems redundant, but makes sure that increasing
  // the hours does no change the date when switching
  // from 11pm up.
  newDate.setFullYear(value.getFullYear());
  newDate.setMonth(value.getMonth());
  newDate.setDate(value.getDate());
  return newDate;
};
 
/** Creates a date but allows the month and date to overflow. */
const createDateInternal = (year: number, month: number, date: number): Date => {
  const d = new Date();
  d.setFullYear(year, month, date);
  d.setHours(0, 0, 0, 0);
  return d;
};
 
const NAMED_FORMATS: { [localeId: string]: { [format: string]: string } } = {};
const INVALID_DATE = new Date(NaN);
/**
 * @param input - String containing a date or dateTime value (Ex. "05/15/2020"
 * @param format - Format of the input value (Ex. "M/d/YYYY")
 * @param locale - Locale of the input value
 * @returns A JS Date in accordance of the three parameters
 */
export const parseDate = (input: string, format: string, locale: string): Date | undefined => {
  if (!input) {
    return undefined;
  }
 
  const splitFormat = format.split(/[^MydhHmsSa]+/);
  const splitDate = input.toUpperCase().match(/\d+|\w+/g);
  if (!splitDate) {
    return INVALID_DATE;
  }
  // in case of some locales where meridian is with special chars
  const dateAndMeridian = input.split(/ +/);
  if (splitDate.length > 0 && dateAndMeridian.length > 0) {
    const parsedMeridian = dateAndMeridian[dateAndMeridian.length - 1].toUpperCase();
    Iif (
      splitDate![splitDate.length - 1] !== parsedMeridian &&
      getMeridian(parsedMeridian, locale)
    ) {
      splitDate?.push(parsedMeridian);
    }
  }
  let year = 0;
  let month = 0;
  /*
    date as in the numeric day of the month to be provided for the Date() constructor.
    default value is 1 since 0 refers to the last date of previous month.
  */
  let date = 1;
  let hour = 0;
  let minute = 0;
  let second = 0;
  let milliseconds = 0;
 
  // check if date is invalid and return if it is invalid
  for (let i = 0; i < splitDate.length; i++) {
    if (i === splitDate.length - 1) {
      const parsedMeridian = splitDate![splitDate.length - 1];
      // skip if its meridian
      if (getMeridian(parsedMeridian, locale)) {
        continue;
      }
    }
    const parsedDateVal = parseInt(splitDate![i], 10);
    if (isNaN(parsedDateVal)) {
      return INVALID_DATE;
    }
  }
 
  for (let i = 0; i < splitFormat.length; i++) {
    const f = splitFormat[i];
    let parsedNumber = parseInt(splitDate![i], 10);
    if (f !== 'a' && isNaN(parsedNumber)) {
      // auto fill seconds and milliseconds if not passed by user
      Iif (f === 'ss' || f === 'SSS') {
        parsedNumber = 0;
      } else {
        return INVALID_DATE;
      }
    }
 
    if (f === 'M' || f === 'MM') {
      month = parsedNumber;
    } else if (f === 'd' || f === 'dd') {
      date = parsedNumber;
    } else if (f === 'y' || f === 'yy' || f === 'yyyy') {
      // JS adds 1900 for numbers between 0 and 99. Adjust to be more user-friendly
      year =
        parsedNumber < 50
          ? parsedNumber + 2000
          : parsedNumber < 100
            ? parsedNumber + 1900
            : parsedNumber;
    } else if (f === 'h' || f === 'HH') {
      hour = parsedNumber;
    } else if (f === 'mm') {
      minute = parsedNumber;
    } else if (f === 'ss') {
      second = parsedNumber;
    } else Iif (f === 'SSS') {
      milliseconds = parsedNumber;
    } else if (f === 'a') {
      Iif (!isNaN(parseInt(splitDate![splitDate!.length - 1], 10))) {
        continue;
      }
      const parsedMeridian = splitDate![splitDate.length - 1];
      const meridian = getMeridian(parsedMeridian, locale);
      Iif (hour === 12 && meridian === 'AM') {
        hour = 0;
      } else if (meridian === 'PM') {
        hour = (hour % 12) + 12;
      } else IEif (!meridian) {
        return INVALID_DATE;
      }
    }
  }
  Iif (month > 12 || date > 31 || date > new Date(year, month, 0).getDate()) {
    return INVALID_DATE;
  }
  return new Date(year, month - 1, date, hour, minute, second, milliseconds);
};
 
const getMeridian = (parsedMeridian: string, locale: string): 'AM' | 'PM' | undefined => {
  const meridian = getLocaleDayPeriods(locale, FormStyle.Format, TranslationWidth.Short);
  const usingAM = parsedMeridian === meridian[0].toUpperCase();
  Iif (usingAM) {
    return 'AM';
  } else {
    const usingPM = parsedMeridian === meridian[1].toUpperCase();
    return usingPM ? 'PM' : undefined;
  }
};
 
// Adapted from: https://github.com/angular/angular/blob/91954cf20e17a386d71cc8ea25d1d17b9ae1e31c/packages/common/src/i18n/format_date.ts
// unfortunately it is not exported there
export const getNamedFormat = (locale: string, format: string): string => {
  const localeId = getLocaleId(locale);
  NAMED_FORMATS[localeId] = NAMED_FORMATS[localeId] || {};
 
  if (NAMED_FORMATS[localeId][format]) {
    return NAMED_FORMATS[localeId][format];
  }
 
  let formatValue = '';
  switch (format) {
    case 'shortDate':
      formatValue = getLocaleDateFormat(locale, FormatWidth.Short);
      break;
    case 'shortTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Short);
      break;
    case 'mediumTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Medium);
      break;
    case 'longTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Long);
      break;
    case 'fullTime':
      formatValue = getLocaleTimeFormat(locale, FormatWidth.Full);
      break;
    case 'short':
    case 'medium':
      {
        const shortTime = getNamedFormat(locale, format === 'short' ? 'shortTime' : 'mediumTime');
        const shortDate = getNamedFormat(locale, 'shortDate');
        formatValue = formatDateTime(getLocaleDateTimeFormat(locale, FormatWidth.Short), [
          shortTime,
          shortDate
        ]);
      }
      break;
  }
  if (formatValue) {
    NAMED_FORMATS[localeId][format] = formatValue;
  }
  return formatValue;
};
 
const formatDateTime = (str: string, optVals: string[]): string => {
  if (optVals) {
    str = str.replace(/\{([^}]+)}/g, (match, key) =>
      optVals != null && key in optVals ? optVals[key] : match
    );
  }
  return str;
};
 
export const getDateWithoutTime = (date: Date): Date => createDate(date, 0, 0, 0, 0);
 
/**
 * Get today
 * @returns date of today
 */
export const today = (): Date => new Date();
 
/**
 * Calculate a new date based on the offset while considering the min and max date.
 * @param current - input date.
 * @param daysOffset - numeric offset of days.
 * @returns new date if the range is valid or original date
 */
export const addDaysInRange = (
  current: Date,
  daysOffset: number,
  minDate?: Date,
  maxDate?: Date
): Date => {
  const newDate = addDays(current, daysOffset);
  // Make sure the new date is within the specified limits
  // MinDate < new data < MaxDate
  if (isSameOrBetween(newDate, minDate, maxDate)) {
    return newDate;
  }
  return getDateSameOrBetween(newDate, minDate, maxDate);
};
 
/**
 * Get date delta based on the offset.
 * @param date - source date object.
 * @param days - numeric offset of days.
 * @returns new date.
 */
export const addDays = (date: Date, days: number): Date => {
  const d = createDate(date);
  d.setDate(d.getDate() + days);
  return d;
};
 
/**
 * Update date/day of give date without changing the month.
 * In case the day exceed the number of days in the current month the last day in month will be assigned.
 * @param date - the date object to update the day.
 * @param day - the day which shall be set.
 * @returns the updated date object.
 */
export const changeDay = (date: Date, day: number): Date => {
  const lastDay = daysInMonth(date.getMonth(), date.getFullYear());
  date.setDate(lastDay <= day ? lastDay : day);
  return date;
};
 
/**
 * Get date delta specifically for months based on the offset.
 * @param current - starting date.
 * @param monthsOffset - numeric offset of months.
 * @param minDate - optional minimum allowed date.
 * @param maxDate - optional maximum allowed date.
 * @returns a new date object with the updated month.
 */
export const addMonthsInRange = (
  current: Date,
  monthsOffset: number,
  minDate?: Date,
  maxDate?: Date
): Date => {
  let newDate = createDateInternal(current.getFullYear(), current.getMonth() + monthsOffset, 1);
  newDate = changeDay(newDate, current.getDate());
  if (isSameOrBetween(newDate, minDate, maxDate)) {
    return newDate;
  }
  return getDateSameOrBetween(newDate, minDate, maxDate);
};
 
/**
 * Get date delta specifically for years based on the offset.
 * @param current - starting date.
 * @param yearsOffset - numeric offset of years.
 * @param minDate - optional minimum allowed date.
 * @param maxDate - optional maximum allowed date.
 * @returns a new date object with the updated year.
 */
export const addYearsInRange = (
  current: Date,
  yearsOffset: number,
  minDate?: Date,
  maxDate?: Date
): Date => {
  const newDate = createDateInternal(
    current.getFullYear() + yearsOffset,
    current.getMonth(),
    current.getDate()
  );
  if (isSameOrBetween(newDate, minDate, maxDate)) {
    return newDate;
  }
  return getDateSameOrBetween(newDate, minDate, maxDate);
};
 
/**
 * Get number of days for the given month and year.
 * @param month - month as number (0..11).
 * @param year - year as number.
 * @returns the number of days for the given month.
 */
export const daysInMonth = (month: number, year: number): number =>
  // By using 0 as the day it will give us the last day of the prior
  // month. So passing in 1 as the month number will return the last day
  new Date(year, month + 1, 0).getDate();
 
/**
 * Get the first date of the week based on the input date.
 * @param current - a date object from where the last date of a week is derived.
 * @param weekStartDay - optional when a week shall start.
 * @returns a new date object which is the start of the current week.
 */
export const getWeekStartDate = (current: Date, weekStartDay: WeekStart = 'monday'): Date => {
  const weekStartDate = createDate(current);
  const diff = current.getDate() - getWeekDayOffset(current, weekStartDay);
  weekStartDate.setDate(diff);
  return weekStartDate;
};
 
/**
 * Get the last date of the week based on the input date.
 * @param current - a date object from where the last date of a week is derived.
 * @param weekStartDay - optional when a week shall start.
 * @returns the last date within the week.
 */
export const getWeekEndDate = (current: Date, weekStartDay: WeekStart = 'monday'): Date => {
  const weekStartDate = createDate(current);
  weekStartDate.setDate(current.getDate() + 6 - getWeekDayOffset(current, weekStartDay));
  return weekStartDate;
};
 
/**
 * Get the beginning of the month.
 * @param current - a date object from where the first date in a month is derived.
 * @returns a new date object which starts a the first.
 */
export const getFirstDateInMonth = (current: Date): Date =>
  new Date(current.getFullYear(), current.getMonth(), 1);
 
/**
 * Get the last date of the month.
 * @param current - a date object from where we derive the last date in a month.
 * @returns a new date object which is the last day in the current month.
 */
export const getLastDateInMonth = (current: Date): Date =>
  new Date(current.getFullYear(), current.getMonth() + 1, 0);
 
/**
 * Get the beginning of the year.
 * @param current - a date object from where the first date in a year is derived.
 * @returns a new date object which starts a the first.
 */
export const getFirstDateInYear = (current: Date): Date => new Date(current.getFullYear(), 0, 1);
 
/**
 * Are the two dates identical without considering time.
 */
export const isSameDate = (current: Date, compareTo?: Date): boolean => {
  if (!compareTo) {
    return false;
  }
  return (
    current.getFullYear() === compareTo.getFullYear() &&
    current.getMonth() === compareTo.getMonth() &&
    current.getDate() === compareTo.getDate()
  );
};
 
/**
 * Are the two months identical without considering time.
 */
export const isSameMonth = (current: Date, compareTo?: Date): boolean => {
  if (!compareTo) {
    return false;
  }
  return isSameYear(current, compareTo) && current.getMonth() === compareTo.getMonth();
};
 
/**
 * Are the two years identical.
 */
export const isSameYear = (current: Date, compareTo?: Date): boolean => {
  Iif (!compareTo) {
    return false;
  }
  return current.getFullYear() === compareTo.getFullYear();
};
/**
 * Compares two dates.
 * @param first - The first date to compare.
 * @param second - The second date to compare.
 * @returns 0 if the dates are equal, a number less than 0 if the first date is earlier,
 * a number greater than 0 if the first date is later.
 */
export const compareDate = (first: Date, second: Date): number =>
  compareMonth(first, second) || first.getDate() - second.getDate();
 
/**
 * Compares two months.
 * @param first - The first month to compare.
 * @param second - The second month to compare.
 * @returns 0 if the months are equal, a number less than 0 if the first month is earlier,
 * a number greater than 0 if the first month is later.
 */
export const compareMonth = (first: Date, second: Date): number =>
  compareYear(first, second) || first.getMonth() - second.getMonth();
 
/**
 * Compares two years.
 * @param first - The first year to compare.
 * @param second - The second year to compare.
 * @returns 0 if the years are equal, a number less than 0 if the first year is earlier,
 * a number greater than 0 if the first year is later.
 */
export const compareYear = (first: Date, second: Date): number =>
  first.getFullYear() - second.getFullYear();
/**
 * Compare the current date is the same date or between start and end date.
 * @param current - the date object.
 * @param from - optional min date, if no value is provided we assume true for the min value.
 * @param to - optional max date, if no value is provided we assume true for the max value.
 * @returns true if the date is in the provided range.
 */
export const isSameOrBetween = (current: Date, from?: Date, to?: Date): boolean => {
  // from <= d
  const isInMinRange = from ? compareDate(from, current) <= 0 : true;
  // d <= to
  const isInMaxRange = to ? compareDate(current, to) <= 0 : true;
  return isInMinRange && isInMaxRange;
};
 
/**
 * Compare the current month is the same month or between start and end month.
 * @param current - the month object.
 * @param from - optional min month, if no value is provided we assume true for the min value.
 * @param to - optional max month, if no value is provided we assume true for the max value.
 * @returns true if the date is in the provided range.
 */
export const isSameOrBetweenMonth = (current: Date, from?: Date, to?: Date): boolean => {
  // from <= d
  const isInMinRange = from ? compareMonth(from, current) <= 0 : true;
  // d <= to
  const isInMaxRange = to ? compareMonth(current, to) <= 0 : true;
  return isInMinRange && isInMaxRange;
};
 
/**
 * Compare the current year is the same year or between start and end year.
 * @param current - the year object.
 * @param from - optional min year, if no value is provided we assume true for the min value.
 * @param to - optional max year, if no value is provided we assume true for the max value.
 * @returns true if the date is in the provided range.
 */
export const isSameOrBetweenYears = (current: Date, from?: Date, to?: Date): boolean => {
  // from <= d
  const isInMinRange = from ? compareYear(from, current) <= 0 : true;
  // d <= to
  const isInMaxRange = to ? compareYear(current, to) <= 0 : true;
  return isInMinRange && isInMaxRange;
};
 
/**
 * Compare the current date is between start and end date.
 * from \< current \< to
 */
export const isBetween = (current: Date, from?: Date, to?: Date): boolean => {
  const isInMinRange = from ? compareDate(current, from) > 0 : true;
  const isInMaxRange = to ? compareDate(current, to) < 0 : true;
  return isInMinRange && isInMaxRange;
};
 
/**
 * Compare the current month is between start and end month.
 * from \< current \< to
 */
export const isBetweenMonth = (current: Date, from?: Date, to?: Date): boolean => {
  const isInMinRange = from ? compareMonth(current, from) > 0 : true;
  const isInMaxRange = to ? compareMonth(current, to) < 0 : true;
  return isInMinRange && isInMaxRange;
};
 
/**
 * Compare the current year is between start and end year.
 * from \< current \< to
 */
export const isBetweenYears = (current: Date, from?: Date, to?: Date): boolean => {
  const isInMinRange = from ? compareYear(current, from) > 0 : true;
  const isInMaxRange = to ? compareYear(current, to) < 0 : true;
  return isInMinRange && isInMaxRange;
};
 
/**
 * Is first date after the second date (without considering the time).
 * current \> compareTo
 */
export const isAfter = (current: Date, compareTo: Date): boolean =>
  compareDate(current, compareTo) > 0;
 
/**
 * Is first month after the second month (without considering the time).
 * current \> compareTo
 */
export const isAfterMonth = (current: Date, compareTo: Date): boolean =>
  compareMonth(current, compareTo) > 0;
 
/**
 * Is first year after the second year.
 * current \> compareTo
 */
export const isAfterYear = (current: Date, compareTo: Date): boolean =>
  compareYear(current, compareTo) > 0;
 
/**
 * Is first date equal or before the second date (without considering the time).
 * current \>= compareTo
 */
export const isSameOrBefore = (current: Date, compareTo: Date): boolean =>
  compareDate(current, compareTo) <= 0;
 
/**
 * Is first month equal or before the second month.
 * current \>= compareTo
 */
export const isSameOrBeforeMonth = (current: Date, compareTo: Date): boolean =>
  compareMonth(current, compareTo) <= 0;
 
/**
 * Is first year equal or before the second year.
 * current \>= compareTo
 */
export const isSameOrBeforeYear = (current: Date, compareTo: Date): boolean =>
  compareMonth(current, compareTo) <= 0;
 
/**
 * Are the two dates in different months.
 */
export const isAnotherMonth = (current: Date, compareTo: Date): boolean =>
  current.getMonth() !== compareTo.getMonth();
 
/**
 * Are the two dates in different years.
 */
export const isAnotherYear = (current: Date, compareTo: Date): boolean =>
  current.getFullYear() !== compareTo.getFullYear();
 
/**
 * Are the two dates either in different months or years.
 */
export const isAnotherMonthOrYear = (current: Date, compareTo: Date): boolean =>
  isAnotherMonth(current, compareTo) || isAnotherYear(current, compareTo);
 
/**
 * Get a date which is in within the range and the close to current.
 */
export const getDateSameOrBetween = (current: Date, minDate?: Date, maxDate?: Date): Date => {
  if (isSameOrBetween(current, minDate, maxDate)) {
    return current;
  }
  const minDistance = minDate
    ? Math.ceil(Math.abs(current.getTime() - minDate!.getTime()))
    : Number.MAX_VALUE;
  const maxDistance = maxDate
    ? Math.ceil(Math.abs(current.getTime() - maxDate!.getTime()))
    : Number.MAX_VALUE;
  return minDistance < maxDistance ? createDate(minDate!) : createDate(maxDate!);
};
 
/**
 * Get date or absolute min date.
 * @param date - input date.
 * @returns date or date of 1.1.1900
 */
export const getMinDate = (date?: Date): Date =>
  date && !isNaN(date.getTime()) ? date : new Date(Date.UTC(1900, 0, 1));
 
/**
 * Get date or absolute max date.
 * @param date - input date.
 * @returns date or date of 31.12.2154
 */
export const getMaxDate = (date?: Date): Date =>
  date && !isNaN(date.getTime()) ? date : new Date(Date.UTC(2154, 11, 31));
 
/**
 * Is valid date object.
 */
export const isValid = (date?: Date): date is NonNullable<Date> => !!date && !isNaN(date.getTime());
 
/**
 * Returns the next months of the given date.
 * @param date - The date for which the next month is returned.
 * @returns A date of the first day of the following month of the given day.
 */
export const nextMonth = (date: Date): Date => {
  Iif (date.getMonth() === 11) {
    return new Date(date.getFullYear() + 1, 0, 1);
  } else {
    return new Date(date.getFullYear(), date.getMonth() + 1, 1);
  }
};
 
/**
 * Returns the last day of the previous month of the given date object.
 * @param date - The date for which the previous month is returned.
 * @returns A date of the last day of the previous month of the given day.
 */
export const previousMonth = (date: Date): Date => {
  Iif (date.getMonth() === 0) {
    return new Date(date.getFullYear() - 1, 12, 0);
  } else {
    return new Date(date.getFullYear(), date.getMonth(), 0);
  }
};
 
export const minDate = (first?: Date, second?: Date): Date | undefined => {
  return !!first && !!second ? (first < second ? first : second) : (first ?? second);
};
 
export const maxDate = (first?: Date, second?: Date): Date | undefined => {
  return !!first && !!second ? (first > second ? first : second) : (first ?? second);
};