All files / src dateutils.ts

0% Statements 0/40
0% Branches 0/24
0% Functions 0/9
0% Lines 0/37

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                                                                                                                                                                         
import XDate from 'xdate';
 
export function sameMonth(a: XDate, b: XDate): boolean {
  return a instanceof XDate && b instanceof XDate &&
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth();
}
 
export function sameDate(a: XDate, b: XDate): boolean {
  return a instanceof XDate && b instanceof XDate &&
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate();
}
 
export function monthName(month: number): string {
  return XDate.locales[XDate.defaultLocale].monthNames[month];
}
 
export function isGTE(a: XDate, b: XDate): boolean {
  return b.diffDays(a) > -1;
}
 
export function isLTE(a: XDate, b: XDate): boolean {
  return a.diffDays(b) > -1;
}
 
export function fromTo(a: XDate, b: XDate): XDate[] {
  const days: XDate[] = [];
  let from = +a, to = +b;
  for (; from <= to; from = new XDate(from, true).addDays(1).getTime()) {
    days.push(new XDate(from, true));
  }
  return days;
}
 
export function month(xd: XDate): XDate[] {
  const year = xd.getFullYear(), month = xd.getMonth();
  const days = new Date(year, month + 1, 0).getDate();
 
  const firstDay = new XDate(year, month, 1, 0, 0, 0, true);
  const lastDay = new XDate(year, month, days, 0, 0, 0, true);
 
  return fromTo(firstDay, lastDay);
}
 
export function weekDayNames(firstDayOfWeek: number = 0): string[] {
  let weekDaysNames = XDate.locales[XDate.defaultLocale].dayNamesShort;
  const dayShift = firstDayOfWeek % 7;
  if (dayShift) {
    weekDaysNames = weekDaysNames.slice(dayShift).concat(weekDaysNames.slice(0, dayShift));
  }
  return weekDaysNames;
}
 
export function page(xd: XDate, firstDayOfWeek: number): XDate[] {
  const days = month(xd);
  let before: XDate[] = [], after: XDate[] = [];
 
  const fdow = ((7 + firstDayOfWeek) % 7) || 7;
  const ldow = (fdow + 6) % 7;
 
  firstDayOfWeek = firstDayOfWeek || 0;
 
  const from = days[0].clone();
  if (from.getDay() !== fdow) {
    from.addDays(-(from.getDay() + 7 - fdow) % 7);
  }
 
  const to = days[days.length - 1].clone();
  const day = to.getDay();
  if (day !== ldow) {
    to.addDays((ldow + 7 - day) % 7);
  }
 
  if (isLTE(from, days[0])) {
    before = fromTo(from, days[0]);
  }
 
  if (isGTE(to, days[days.length - 1])) {
    after = fromTo(days[days.length - 1], to);
  }
 
  return before.concat(days.slice(1, days.length - 1), after);
}