date-fns#eachDayOfInterval TypeScript Examples
The following examples show how to use
date-fns#eachDayOfInterval.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dateUtils.tsx From symphony-ui-toolkit with Apache License 2.0 | 6 votes |
/**
* Return a list of translated weekdays, the starting day depends on locale
* @param date
* @param locale
* @param pattern
*/
function getWeekdays(date: Date, locale: Locale, pattern: string): string[] {
const arr = eachDayOfInterval({
start: startOfWeek(date, { locale }),
end: endOfWeek(date, { locale }),
});
return arr.map((item) => {
return format(item, pattern, { locale });
});
}
Example #2
Source File: nights.ts From nyxo-app with GNU General Public License v3.0 | 6 votes |
getNightsAsDays = createSelector(getNights, (nights) => {
const days = eachDayOfInterval({
start: subDays(new Date(), 30),
end: new Date() // lastDate
})
return days.map((day) => ({
date: day.toISOString(),
inBedDuration: 0,
asleepDuration: 0,
night: nights
.filter((night) => matchDayAndNight(night.startDate, day.toISOString()))
.map((night) => {
const startDifference = differenceInMilliseconds(
new Date(night.startDate),
startOfDay(new Date(day))
)
const newStartDate = addMilliseconds(
startOfDay(new Date()),
startDifference
)
const newEndDate = addMinutes(newStartDate, night.totalDuration)
return {
...night,
startDate: newStartDate.valueOf(),
endDate: newEndDate.valueOf()
}
})
}))
})
Example #3
Source File: SleepChart.tsx From nyxo-website with MIT License | 6 votes |
getNightAsDays = (nights: Night[]) => {
const firstDate = min([...nights.map((night) => new Date(night.startDate))])
const lastDate = max([...nights.map((night) => new Date(night.endDate))])
const days = eachDayOfInterval({
start: subDays(new Date(), 30),
end: new Date(), // lastDate
})
return days.map((day) => ({
date: day.toISOString(),
night: nights
.filter((night) => matchDayAndNight(night.startDate, day.toISOString()))
.map((night) => {
const startDifference = differenceInMilliseconds(
new Date(night.startDate),
startOfDay(new Date(day))
)
const newStartDate = addMilliseconds(
startOfDay(new Date()),
startDifference
)
const newEndDate = addMinutes(newStartDate, night.totalDuration)
return {
...night,
startDate: newStartDate.valueOf(),
endDate: newEndDate.valueOf(),
}
}),
}))
}
Example #4
Source File: dategrid.ts From calendar-hack with MIT License | 6 votes |
selectAll(dow: dayOfWeek) {
if (!this.first || !this.last) return []
const dates = eachDayOfInterval({ start: this.first, end: this.last });
switch (dow) {
case 'Monday':
return dates.filter(d => isMonday(d));
case 'Tuesday':
return dates.filter(d => isTuesday(d));
case 'Wednesday':
return dates.filter(d => isWednesday(d));
case 'Thursday':
return dates.filter(d => isThursday(d));
case 'Friday':
return dates.filter(d => isFriday(d));
case 'Saturday':
return dates.filter(d => isSaturday(d));
case 'Sunday':
return dates.filter(d => isSunday(d));
default:
throw new Error(`unhandled day of week ${dow}`);
}
}
Example #5
Source File: planbuilder.ts From calendar-hack with MIT License | 6 votes |
export function build(trainingPlan: TrainingPlan, raceDate: Date): RacePlan {
const planDates = calcPlanDates(trainingPlan.schedule.length, raceDate);
const workoutsToPlace = getWorkouts(trainingPlan);
const map = new Map<Date, DayDetails>();
eachDayOfInterval({ start: planDates.planStartDate, end: planDates.planEndDate }).forEach(currDate => {
const dayDetails = renderDayDetails(currDate, trainingPlan.units, workoutsToPlace.shift())
if (dayDetails) {
map.set(currDate, dayDetails);
}
});
const dateGrid = new DateGrid(map);
return { raceType: trainingPlan.type, planDates: planDates, dateGrid: dateGrid, sourceUnits: trainingPlan.units, description: trainingPlan.description, sourceUrl: trainingPlan.source };
}
Example #6
Source File: MonthlyCalendar.tsx From react-calendar with MIT License | 6 votes |
MonthlyCalendar = ({
locale,
currentMonth,
onCurrentMonthChange,
children,
}: Props) => {
let monthStart = startOfMonth(currentMonth);
let days = eachDayOfInterval({
start: monthStart,
end: endOfMonth(monthStart),
});
return (
<MonthlyCalendarContext.Provider
value={{
days,
locale,
onCurrentMonthChange,
currentMonth: monthStart,
}}
>
{children}
</MonthlyCalendarContext.Provider>
);
}
Example #7
Source File: useAvailableSaveApy.ts From mStable-apps with GNU Lesser General Public License v3.0 | 5 votes |
timestampsForMonth = eachDayOfInterval({ start: subDays(now, 29), end: subDays(now, 1), }) .map(endOfDay) .concat(now)
Example #8
Source File: formatters.ts From mStable-apps with GNU Lesser General Public License v3.0 | 5 votes |
periodIntervalMapping: Record<TimeMetricPeriod, (interval: Interval) => Date[]> = {
[TimeMetricPeriod.Hour]: eachHourOfInterval,
[TimeMetricPeriod.Day]: eachDayOfInterval,
[TimeMetricPeriod.Week]: eachWeekOfInterval,
[TimeMetricPeriod.Month]: eachMonthOfInterval,
[TimeMetricPeriod.Quarter]: eachQuarterOfInterval,
[TimeMetricPeriod.Year]: eachYearOfInterval,
}
Example #9
Source File: dategrid.ts From calendar-hack with MIT License | 5 votes |
selectWeek(weekNum: number) {
if (!this.first || !this.last) return []
const d1 = addWeeks(this.first, weekNum);
const d2 = addDays(d1, 6);
return eachDayOfInterval({ start: d1, end: d2 });
}
Example #10
Source File: chartDataHelper.ts From korona-info with MIT License | 5 votes |
getTimeSeriesData = (
confirmed: Confirmed[],
// recovered: Recovered[],
deaths: Deaths[]
): TimeSeriesData => {
const sortedData = sortBy(confirmed, 'date').map(item => ({
...item,
dateString: format(new Date(item.date), 'yyyy-MM-dd')
}));
// const sortedDataRecoverd = sortBy(recovered, 'date').map(item => ({
// ...item,
// dateString: format(new Date(item.date), 'yyyy-MM-dd')
// }));
const sortedDataDeaths = sortBy(deaths, 'date').map(item => ({
...item,
dateString: format(new Date(item.date), 'yyyy-MM-dd')
}));
const today = new Date();
const startDate = new Date(sortedData[0]?.date ?? today);
const days30Ago = subDays(today, 30);
const daysIntervalSinceFirstInfection = eachDayOfInterval({
start: startDate.getTime() > days30Ago.getTime() ? days30Ago : startDate,
end: today
});
const infectionDevelopmentData: InfectionDevelopmentDataItem[] = [];
daysIntervalSinceFirstInfection.reduce(
(
acc: {
// recovered: number;
infections: number;
deaths: number;
},
curr
) => {
const items = sortedData.filter(item =>
isSameDay(new Date(item.date), curr)
);
// const itemsRecovered = sortedDataRecoverd.filter(item =>
// isSameDay(new Date(item.date), curr)
// );
const itemsDeaths = sortedDataDeaths.filter(item =>
isSameDay(new Date(item.date), curr)
);
acc.deaths = acc.deaths + itemsDeaths.length;
acc.infections = acc.infections + items.length;
// acc.recovered = acc.recovered + itemsRecovered.length;
infectionDevelopmentData.push({
date: curr.getTime(),
infectionsDaily: items.length,
...acc
});
return acc;
},
{ infections: 0, deaths: 0 }
);
const thirtyDaysAgo = subDays(today, 30);
const infectionDevelopmentData30Days = infectionDevelopmentData.filter(
item => item.date > thirtyDaysAgo.getTime()
);
return {
infectionDevelopmentData,
infectionDevelopmentData30Days
};
}
Example #11
Source File: dategrid.test.ts From calendar-hack with MIT License | 4 votes |
describe('Plan', function () {
it('initially empty grid', function () {
let p = new DateGrid(new Map());
expect(p).not.toBeNull();
expect(p.min).toBeUndefined();
expect(p.max).toBeUndefined();
expect(p.first).toBeUndefined();
expect(p.last).toBeUndefined();
expect(p.days).toEqual([]);
expect(p.weeks).toEqual([]);
expect(p.weekCount).toEqual(0);
});
it('grid spanning one week with one date on it', function () {
const m = new Map();
const d = dparse('4/19/2020'); // A Sunday
const testEvent = { desc: 'event-1' };
const expectedDays = [
{ date: dparse('4/13/2020'), event: undefined },
{ date: dparse('4/14/2020'), event: undefined },
{ date: dparse('4/15/2020'), event: undefined },
{ date: dparse('4/16/2020'), event: undefined },
{ date: dparse('4/17/2020'), event: undefined },
{ date: dparse('4/18/2020'), event: undefined },
{ date: dparse('4/19/2020'), event: testEvent },
];
m.set(d, testEvent);
let p = new DateGrid<Event>(m);
expect(p).not.toBeNull();
expect(p.min).toEqual(d);
expect(p.max).toEqual(d);
expect(p.first).toEqual(dparse('4/13/2020'));
expect(p.last).toEqual(d);
expect(p.days).toEqual(expectedDays);
expect(p.weekCount).toEqual(1);
expect(p.weeks).toEqual([{ weekNum: 0, dist: 0, desc: 'Week 0', days: expectedDays }]);
});
it('grid spanning two weeks with two dates on it', function () {
const m = new Map();
const eventOne = { desc: 'event-1' };
const eventTwo = { desc: 'event-2' };
m.set(dparse('5/7/2020'), eventOne); // Thursday
m.set(dparse('5/16/2020'), eventTwo); // Saturday
const expectedDaysWeek1 = [
{ date: dparse('5/4/2020'), event: undefined },
{ date: dparse('5/5/2020'), event: undefined },
{ date: dparse('5/6/2020'), event: undefined },
{ date: dparse('5/7/2020'), event: eventOne },
{ date: dparse('5/8/2020'), event: undefined },
{ date: dparse('5/9/2020'), event: undefined },
{ date: dparse('5/10/2020'), event: undefined },
];
const expectedDaysWeek2 = [
{ date: dparse('5/11/2020'), event: undefined },
{ date: dparse('5/12/2020'), event: undefined },
{ date: dparse('5/13/2020'), event: undefined },
{ date: dparse('5/14/2020'), event: undefined },
{ date: dparse('5/15/2020'), event: undefined },
{ date: dparse('5/16/2020'), event: eventTwo },
{ date: dparse('5/17/2020'), event: undefined },
];
let p = new DateGrid<Event>(m);
expect(p).not.toBeNull();
expect(p.min).toEqual(dparse('5/7/2020'));
expect(p.max).toEqual(dparse('5/16/2020'));
expect(p.first).toEqual(dparse('5/4/2020'));
expect(p.last).toEqual(dparse('5/17/2020'));
expect(p.days).toEqual(expectedDaysWeek1.concat(expectedDaysWeek2));
expect(p.weekCount).toEqual(2);
expect(p.weeks).toEqual([
{ weekNum: 0, dist: 0, desc: 'Week 0', days: expectedDaysWeek1 },
{ weekNum: 1, dist: 0, desc: 'Week 1', days: expectedDaysWeek2 },
]);
});
it('Should swap two dates correctly', function () {
const firstDay = dparse('04/13/2020');
const secondDay = dparse('04/14/2020');
const lastDay = dparse('04/19/2020');
const m = new Map();
eachDayOfInterval({ start: firstDay, end: lastDay }).forEach(d => {
m.set(d, { desc: format(d, 'MM/dd/yyyy') });
});
const p = new DateGrid(m);
expect(p.days.length).toEqual(7);
expect(p.getEvent(firstDay)).toEqual({ desc: '04/13/2020' });
expect(p.getEvent(secondDay)).toEqual({ desc: '04/14/2020' });
p.swap(firstDay, secondDay)
expect(p.getEvent(firstDay)).toEqual({ desc: '04/14/2020' });
expect(p.getEvent(secondDay)).toEqual({ desc: '04/13/2020' });
});
it('Test swap Saturdays and Mondays', function () {
const firstDay = dparse('03/02/2020');
const lastDay = dparse('04/05/2020');
const m = new Map();
eachDayOfInterval({ start: firstDay, end: lastDay }).forEach(d => {
m.set(d, { desc: format(d, 'EEEE MM/dd/yyyy') });
});
const p = new DateGrid(m);
expect(p.days.length).toEqual(35);
expect(() => p.getEvent(dparse('03/01/2020'))).toThrow(/is not within interval/);
expect(p.getEvent(dparse('03/02/2020'))).toEqual({ desc: 'Monday 03/02/2020' });
expect(p.getEvent(dparse('03/03/2020'))).toEqual({ desc: 'Tuesday 03/03/2020' });
expect(p.getEvent(dparse('04/05/2020'))).toEqual({ desc: 'Sunday 04/05/2020' });
p.swapDow('Tuesday', 'Wednesday');
const tuesdays = ['03/03/2020', '03/10/2020', '03/17/2020', '03/24/2020', '03/31/2020'];
expect(p.selectAll('Tuesday').map(fmt)).toEqual(tuesdays);
const wednesdays = ['03/04/2020', '03/11/2020', '03/18/2020', '03/25/2020', '04/01/2020'];
expect(p.selectAll('Wednesday').map(fmt)).toEqual(wednesdays);
tuesdays.forEach(s => expect(p.getEvent(dparse(s))?.desc.startsWith('Wednesday')).toBe(true));
wednesdays.forEach(s => expect(p.getEvent(dparse(s))?.desc.startsWith('Tuesday')).toBe(true));
});
});