date-fns#subDays TypeScript Examples
The following examples show how to use
date-fns#subDays.
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: dummyEvents.ts From react-calendar with MIT License | 6 votes |
events: { [key: string]: EventType[] } = {
firstMonth: [
{ title: 'Call John', date: subHours(new Date(), 2) },
{ title: 'Call John', date: subHours(new Date(), 1) },
{ title: 'Meeting with Bob', date: new Date() },
{ title: 'Bike Appt', date: addHours(new Date(), 3) },
{ title: 'John Hilmer', date: addDays(new Date(), 3) },
{ title: 'Jane Call', date: subDays(new Date(), 4) },
{ title: 'Sound alarm', date: addDays(new Date(), 6) },
{ title: 'Soccer Practice', date: subDays(new Date(), 3) },
{ title: 'Alert', date: addHours(subDays(new Date(), 4), 4) },
{ title: 'Donation', date: addDays(new Date(), 6) },
],
secondMonth: [
{ title: 'Meeting Next Month', date: addMonths(new Date(), 1) },
],
}
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: datecalc.ts From calendar-hack with MIT License | 6 votes |
export function calcPlanDates(planWeeks: number, planEndsOn: Date): PlanDates {
const end = startOfDay(endOfWeek(planEndsOn, { weekStartsOn: 1 }));
const planStart = subDays(planEndsOn, planWeeks * 7 - 1);
const start = startOfWeek(planStart, { weekStartsOn: 1 });
const totalDays = 1 + differenceInCalendarDays(end, start);
if (0 !== totalDays % 7) {
throw new Error("total days %7 !==0: " + totalDays);
}
const weekCount = totalDays / 7;
let result = {
start: start,
planStartDate: planStart,
planEndDate: planEndsOn, // before or on race day
end: end, // race day or beyond
weekCount: weekCount
}
return result;
}
Example #5
Source File: bookings.ts From office-booker with MIT License | 6 votes |
getUserBookings = async (
config: Config,
userEmail: string
): Promise<BookingsModel[]> => {
const lowerBound = subDays(new Date().getTime(), config.dataRetentionDays);
const upperBound = addDays(new Date().getTime(), config.advanceBookingDays);
const mapper = buildMapper(config);
const rows: BookingsModel[] = [];
for await (const item of mapper.query(
BookingsModel,
{ user: userEmail },
{
filter: {
type: 'Between',
subject: 'date',
lowerBound: format(lowerBound, 'yyyy-MM-dd'),
upperBound: format(upperBound, 'yyyy-MM-dd'),
},
}
)) {
rows.push(item);
}
return rows;
}
Example #6
Source File: checkin.ts From rcvr-app with GNU Affero General Public License v3.0 | 6 votes |
export async function getVisibleCheckins(): Promise<Checkin[]> {
const SHOW_FROM_LAST_DAYS = 28
const checkins = await db.checkins
.where('enteredAt')
.above(subDays(new Date(), SHOW_FROM_LAST_DAYS))
.reverse()
.sortBy('enteredAt')
.catch(() =>
// We need to return a clone to trigger a repaint
checkinsState.slice(0)
)
return checkins
}
Example #7
Source File: calendarEvents.ts From matx-angular with MIT License | 6 votes |
public events: any[] = [{
_id: '100',
start: subDays(startOfDay(new Date()), 1),
end: addDays(new Date(), 1),
title: 'A 3 day event',
color: this.colors.red
}, {
_id: '101',
start: startOfDay(new Date()),
title: 'An event with no end date',
color: this.colors.yellow
}, {
_id: '102',
start: subDays(endOfMonth(new Date()), 3),
end: addDays(endOfMonth(new Date()), 3),
title: 'A long event that spans 2 months',
color: this.colors.blue
}, {
_id: '103',
start: addHours(startOfDay(new Date()), 2),
end: new Date(),
title: 'A draggable and resizable event',
color: this.colors.yellow,
resizable: {
beforeStart: true,
afterEnd: true
},
draggable: true
}];
Example #8
Source File: utils.ts From ncov with MIT License | 6 votes |
lastWhatDay = (num: number) => {
const whatDayStart = subDays(new Date(), num);
return [_dateFn(whatDayStart), _dateFn(new Date())];
}
Example #9
Source File: utils.ts From ncov with MIT License | 6 votes |
lastWhatDaysList = (num: number) => {
const daysList = [];
for (let i = 1; i < num + 2; i++) {
daysList.push(_dateFn(subDays(new Date(), i)));
}
return daysList.sort();
}
Example #10
Source File: Metrics.tsx From mStable-apps with GNU Lesser General Public License v3.0 | 6 votes |
DATE_RANGES: State<never>['dates'] = [
{
dateRange: DateRange.Day,
period: TimeMetricPeriod.Hour,
label: '24 hour',
from: startOfHour(subHours(new Date(), 23)),
end: END_OF_HOUR,
},
{
dateRange: DateRange.Week,
period: TimeMetricPeriod.Day,
label: '7 day',
from: startOfDay(subDays(new Date(), 6)),
end: END_OF_DAY,
},
{
dateRange: DateRange.Month,
period: TimeMetricPeriod.Day,
label: '30 day',
from: startOfDay(subDays(new Date(), 29)),
end: END_OF_DAY,
},
{
dateRange: DateRange.Days90,
period: TimeMetricPeriod.Day,
label: '90 day',
from: startOfDay(subDays(new Date(), 90)),
end: END_OF_DAY,
},
]
Example #11
Source File: Events.test.tsx From react-calendar with MIT License | 6 votes |
test('Renders full week initially', () => {
render(
<WeeklyCalendarTest
week={new Date(testDate)}
events={[
{ title: 'Janet smith', date: subDays(new Date(testDate), 2) },
{ title: 'Max Smith', date: subDays(new Date(testDate), 1) },
{ title: 'Code', date: subHours(new Date(testDate), 4) },
]}
/>
);
// check that all 3 are on screen
screen.getByText('Janet smith');
screen.getByText('Max Smith');
screen.getByText('Code');
screen.getByText('Mar 1st 24:00');
});
Example #12
Source File: Events.test.tsx From react-calendar with MIT License | 6 votes |
test('Hides event from next week', () => {
render(
<WeeklyCalendarTest
week={new Date(testDate)}
events={[
{ title: 'Janet smith', date: subDays(new Date(testDate), 2) },
{ title: 'Max Smith', date: subDays(new Date(testDate), 1) },
{ title: 'Code', date: subHours(new Date(testDate), 4) },
{ title: 'Next week', date: addDays(new Date(testDate), 7) },
]}
/>
);
// check that all 3 are on screen
screen.getByText('Janet smith');
screen.getByText('Max Smith');
screen.getByText('Code');
screen.getByText('Mar 1st 24:00');
expect(screen.queryByText('Next week')).toEqual(null);
});
Example #13
Source File: Events.test.tsx From react-calendar with MIT License | 6 votes |
test('Renders single day after click', () => {
render(
<WeeklyResponsiveContainer>
<WeeklyCalendarTest
week={new Date(testDate)}
events={[
{ title: 'Janet smith', date: subDays(new Date(testDate), 3) },
{ title: 'Max Smith', date: subDays(new Date(testDate), 1) },
{ title: 'Code', date: subHours(new Date(testDate), 4) },
]}
/>
</WeeklyResponsiveContainer>
);
fireEvent.click(screen.getByText('Sunday 28th'));
screen.getByText('Janet smith');
expect(screen.queryByText('Max Smith')).toEqual(null);
expect(screen.queryByText('Code')).toEqual(null);
screen.getByText('24:00');
});
Example #14
Source File: Events.test.tsx From react-calendar with MIT License | 6 votes |
test('Renders week after clicking a selected day', () => {
render(
<WeeklyCalendarTest
week={new Date(testDate)}
events={[
{ title: 'Janet smith', date: subDays(new Date(testDate), 3) },
{ title: 'Max Smith', date: subDays(new Date(testDate), 1) },
{ title: 'Code', date: subHours(new Date(testDate), 4) },
]}
/>
);
fireEvent.click(screen.getByText('Sunday 28th'));
screen.getByText('Janet smith');
expect(screen.queryByText('Max Smith')).toEqual(null);
expect(screen.queryByText('Code')).toEqual(null);
fireEvent.click(screen.getByText('Sunday 28th'));
// check that all 3 are on screen
screen.getByText('Janet smith');
screen.getByText('Max Smith');
screen.getByText('Code');
});
Example #15
Source File: Events.test.tsx From react-calendar with MIT License | 6 votes |
test('Renders using a custom locale', () => {
render(
<WeeklyCalendarTest
locale={zhCN}
week={new Date(testDate)}
events={[
{ title: 'Janet smith', date: subDays(new Date(testDate), 2) },
{ title: 'Max Smith', date: subDays(new Date(testDate), 1) },
{ title: 'Code', date: subHours(new Date(testDate), 4) },
]}
/>
);
// check that all 3 are on screen
screen.getByText('Janet smith');
screen.getByText('Max Smith');
screen.getByText('Code');
screen.getByText('3月 1日 24:00');
});
Example #16
Source File: OmitDays.test.tsx From react-calendar with MIT License | 6 votes |
test('Renders all days of the week', () => {
render(
<WeeklyCalendarTest
week={new Date(testDate)}
events={[
{ title: 'Janet smith', date: subDays(new Date(testDate), 2) },
{ title: 'Max Smith', date: subDays(new Date(testDate), 1) },
{ title: 'Code', date: subHours(new Date(testDate), 4) },
]}
/>
);
expect(screen.getAllByLabelText('Day of Week').length).toEqual(7);
});
Example #17
Source File: OmitDays.test.tsx From react-calendar with MIT License | 6 votes |
test('Omits the weekends', () => {
render(
<WeeklyCalendarTest
week={new Date(testDate)}
omitDays={[6, 0]}
events={[
{ title: 'Janet smith', date: subDays(new Date(testDate), 2) },
{ title: 'Max Smith', date: subDays(new Date(testDate), 1) },
{ title: 'Code', date: subHours(new Date(testDate), 4) },
]}
/>
);
expect(screen.getAllByLabelText('Day of Week').length).toEqual(5);
expect(screen.queryByText('Saturday 6th')).toEqual(null);
expect(screen.queryByText('Sunday 28th')).toEqual(null);
});
Example #18
Source File: auth.service.ts From amplication with Apache License 2.0 | 6 votes |
/**
* Validates that the provided token of the provided user exist and not expired.
* In case it is valid, it updates the "LastAccessAt" with current date and time
*/
async validateApiToken(args: {
userId: string;
tokenId: string;
token: string;
}): Promise<boolean> {
const lastAccessThreshold = subDays(new Date(), TOKEN_EXPIRY_DAYS);
const apiToken = await this.prismaService.apiToken.updateMany({
where: {
userId: args.userId,
id: args.tokenId,
lastAccessAt: {
gt: lastAccessThreshold
},
user: {
deletedAt: null
}
},
data: {
lastAccessAt: new Date()
}
});
if (apiToken.count === 1) {
return true;
}
return false;
}
Example #19
Source File: deployment.service.ts From amplication with Apache License 2.0 | 6 votes |
/**
* Destroy staled environments
* This function should be called periodically from an external scheduler
*/
async destroyStaledDeployments(): Promise<void> {
const lastDeployThreshold = subDays(
new Date(),
DESTROY_STALED_INTERVAL_DAYS
);
const environments = await this.prisma.environment.findMany({
where: {
deployments: {
some: {
createdAt: {
lt: lastDeployThreshold
},
status: {
equals: EnumDeploymentStatus.Completed
}
}
}
},
take: MAX_DESTROY_PER_CYCLE
});
await Promise.all(
environments.map(async environment => {
return this.destroy(environment.id);
})
);
}
Example #20
Source File: dateFormat.spec.ts From apps with GNU Affero General Public License v3.0 | 6 votes |
describe('getReadHistoryDateFormat', () => {
it('should return formatted date for the same day', () => {
const expected = 'Today';
const date = new Date();
const actual = getReadHistoryDateFormat(date);
expect(actual).toEqual(expected);
});
it('should return formatted date for the day before', () => {
const expected = 'Yesterday';
const date = subDays(new Date(), 1);
const actual = getReadHistoryDateFormat(date);
expect(actual).toEqual(expected);
});
it('should return formatted date for the same year', () => {
const year = new Date().getFullYear();
const date = new Date(`${year}-03-31 07:15:51.247`);
const weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][
date.getDay()
];
const expected = getLabel(date) || `${weekday}, 31 Mar`;
const actual = getReadHistoryDateFormat(date);
expect(actual).toEqual(expected);
});
it('should return formatted date with a different year from today', () => {
const expected = 'Sat, 31 Mar 2018';
const date = new Date('2018-03-31 07:15:51.247');
const actual = getReadHistoryDateFormat(date);
expect(actual).toEqual(expected);
});
});
Example #21
Source File: dateFormat.ts From apps with GNU Affero General Public License v3.0 | 6 votes |
export function postDateFormat(
value: Date | number | string,
now = new Date(),
): string {
const date = new Date(value);
// Calculate time delta in seconds.
const dt = (now.getTime() - date.getTime()) / 1000;
if (dt <= oneMinute) return 'Now';
if (isSameDay(date, now)) {
return 'Today';
}
if (isSameDay(date, subDays(now, 1))) return 'Yesterday';
return date.toLocaleString('en-US', {
month: 'short',
day: '2-digit',
year: 'numeric',
});
}
Example #22
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 #23
Source File: getUtcSecondsFromDayRange.ts From beefy-api with MIT License | 5 votes |
getUtcSecondsFromDayRange = (daysAgo0: number, daysAgo1: number) => {
const endDate = startOfMinute(subDays(Date.now(), daysAgo0));
const startDate = startOfMinute(subDays(Date.now(), daysAgo1));
const [start, end] = [startDate, endDate].map(getUTCSeconds);
return [start, end];
}
Example #24
Source File: ProfilePage.tsx From apps with GNU Affero General Public License v3.0 | 5 votes |
after = subMonths(subDays(before, 2), 6)
Example #25
Source File: Weekly.stories.tsx From react-calendar with MIT License | 5 votes |
BasicWeeklyCalendar: Story = args => {
return (
<WeeklyResponsiveContainer>
<WeeklyCalendar week={args.week}>
<WeeklyContainer>
<WeeklyDays omitDays={args.hideWeekend ? [0, 6] : undefined} />
<WeeklyBody
style={{ maxHeight: args.hideWeekend ? '18rem' : '26rem' }}
events={[
{ title: 'Janet smith', date: subDays(new Date(), 3) },
{ title: 'Max Smith', date: subDays(new Date(), 1) },
{ title: 'Code', date: subHours(new Date(), 4) },
{ title: 'Call Emma', date: subHours(new Date(), 3) },
{ title: 'Eat lunch', date: subHours(new Date(), 2) },
{ title: 'Sleep', date: subHours(new Date(), 1) },
{ title: 'Meeting with Bob', date: new Date() },
{ title: 'John smith', date: addDays(new Date(), 1) },
{ title: 'Jane doe', date: addDays(new Date(), 3) },
{ title: 'Janet smith', date: subDays(new Date(), 4) },
{ title: 'Max Smith', date: subDays(new Date(), 5) },
{ title: 'John smith', date: addDays(new Date(), 4) },
{ title: 'Jane doe', date: addDays(new Date(), 5) },
]}
renderItem={({ item, showingFullWeek }) => (
<DefaultWeeklyEventItem
key={item.date.toISOString()}
title={item.title}
date={
showingFullWeek
? format(item.date, 'MMM do k:mm')
: format(item.date, 'k:mm')
}
/>
)}
/>
</WeeklyContainer>
</WeeklyCalendar>
</WeeklyResponsiveContainer>
);
}
Example #26
Source File: infoQueryHelpers.ts From vvs-ui with GNU General Public License v3.0 | 5 votes |
getDeltaTimestamps = (): [number, number, number, number] => {
const utcCurrentTime = getUnixTime(new Date()) * 1000
const t24h = getUnixTime(startOfMinute(subDays(utcCurrentTime, 1)))
const t48h = getUnixTime(startOfMinute(subDays(utcCurrentTime, 2)))
const t7d = getUnixTime(startOfMinute(subWeeks(utcCurrentTime, 1)))
const t14d = getUnixTime(startOfMinute(subWeeks(utcCurrentTime, 2)))
return [t24h, t48h, t7d, t14d]
}
Example #27
Source File: calculate.ts From roamjs-com with MIT License | 5 votes |
calculateExpression = (expression: Expression): string => {
const args = expression.children
.flatMap((c) => calculateExpression(c).split(DELIM))
.filter((a) => !!a);
switch (expression.operation) {
case "+":
return args
.reduce((total, current) => total + parseInt(current), 0)
.toString();
case "-":
return args.slice(1).reduce((total, current) => {
if (DAILY_NOTE_PAGE_REGEX.test(total)) {
const totalDate = parseRoamDate(extractTag(total));
if (DAILY_NOTE_PAGE_REGEX.test(current)) {
return Math.abs(
differenceInDays(totalDate, parseRoamDate(extractTag(current)))
).toString();
} else {
return toRoamDate(subDays(totalDate, parseInt(current)));
}
}
return (parseInt(total) - parseInt(current)).toString();
}, args[0]);
case "*":
return args
.reduce((total, current) => total * parseInt(current), 1)
.toString();
case "/":
return args
.slice(1)
.reduce(
(total, current) => total / parseInt(current),
parseInt(args[0])
)
.toString();
case "daily":
return getTitlesReferencingPagesInSameBlockTree(args)
.filter((t) => DAILY_NOTE_PAGE_REGEX.test(t))
.join(DELIM);
case "max":
return args.every((s) => DAILY_NOTE_PAGE_REGEX.test(s))
? toRoamDate(
new Date(Math.max(...args.map((s) => parseRoamDate(s).valueOf())))
)
: Math.max(...args.map((s) => parseInt(s))).toString();
case "since":
return args.length
? differenceInDays(new Date(), parseRoamDate(args[0])).toString()
: "0";
case "attr":
return calculateExpression(
parseExpression(getConfigFromPage(args[0])[args[1]] || "0")
);
case "value":
return expression.value.toString();
default:
return "";
}
}
Example #28
Source File: infoQueryHelpers.ts From glide-frontend with GNU General Public License v3.0 | 5 votes |
getDeltaTimestamps = (): [number, number, number, number] => {
const utcCurrentTime = getUnixTime(new Date()) * 1000
const t24h = getUnixTime(startOfMinute(subDays(utcCurrentTime, 1)))
const t48h = getUnixTime(startOfMinute(subDays(utcCurrentTime, 2)))
const t7d = getUnixTime(startOfMinute(subWeeks(utcCurrentTime, 1)))
const t14d = getUnixTime(startOfMinute(subWeeks(utcCurrentTime, 2)))
return [t24h, t48h, t7d, t14d]
}
Example #29
Source File: time.ts From nyxo-app with GNU General Public License v3.0 | 5 votes |
export function toNightTime(date: string): string {
const nightEnd = new Date(date)
const nightStart = startOfDay(subDays(new Date(nightEnd), 1))
return `${format(nightStart, 'dd.MM.')} – ${format(nightStart, 'dd.MM.')}`
}