date-fns#addHours TypeScript Examples
The following examples show how to use
date-fns#addHours.
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: ResetPasswordService.ts From gobarber-api with MIT License | 6 votes |
async execute({ token, password }: IRequest): Promise<void> {
const userToken = await this.userTokensRepository.findByToken(token);
if (!userToken) {
throw new AppError('User token does not exists');
}
const user = await this.usersRepository.findById(userToken.user_id);
if (!user) {
throw new AppError('User does not exists');
}
const tokenCraetedAt = userToken.created_at;
const compareDate = addHours(tokenCraetedAt, 2);
if (isAfter(Date.now(), compareDate)) {
throw new AppError('Token expired');
}
user.password = await this.hashProvider.generateHash(password);
await this.usersRepository.save(user);
}
Example #2
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 #3
Source File: date.ts From ngx-gantt with MIT License | 6 votes |
add(amount: number, unit?: GanttDateUtil) {
switch (unit) {
case 'second':
return new GanttDate(this.value).addSeconds(amount);
case 'minute':
return new GanttDate(this.value).addMinutes(amount);
case 'hour':
return new GanttDate(this.value).addHours(amount);
case 'day':
return new GanttDate(this.value).addDays(amount);
case 'week':
return new GanttDate(this.value).addWeeks(amount);
case 'month':
return new GanttDate(this.value).addMonths(amount);
case 'quarter':
return new GanttDate(this.value).addQuarters(amount);
case 'year':
return new GanttDate(this.value).addYears(amount);
default:
return new GanttDate(this.value).addSeconds(amount);
}
}
Example #4
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 #5
Source File: ResetPasswordService.ts From GoBarber with MIT License | 6 votes |
public async execute({ token, password }: IRequest): Promise<void> {
const userToken = await this.userTokensRepository.findByToken(token);
if (!userToken) {
throw new AppError('User token does not exists');
}
const user = await this.usersRepository.findById(userToken.user_id);
if (!user) {
throw new AppError('User does not exists');
}
const tokenCreatedAt = userToken.created_at;
const compareDate = addHours(tokenCreatedAt, 2);
if (isAfter(Date.now(), compareDate)) {
throw new AppError('Token expired');
}
user.password = await this.hashProvider.generateHash(password);
await this.usersRepository.save(user);
}
Example #6
Source File: ResetPasswordService.ts From gobarber-project with MIT License | 6 votes |
public async execute({ token, password }: IRequest): Promise<void> {
const userToken = await this.userTokensRepository.findByToken(token);
if (!userToken) {
throw new AppError('User Token does not exists');
}
const user = await this.usersRepository.findById(userToken.user_id);
if (!user) {
throw new AppError('User Token does not exists');
}
const tokenCreatedAt = userToken.created_at;
const compareDate = addHours(tokenCreatedAt, 2);
if (isAfter(Date.now(), compareDate)) {
throw new AppError('Token expired');
}
user.password = await this.hashProvider.generateHash(password);
await this.usersRepository.save(user);
}
Example #7
Source File: RecoverPasswordRequestsRepository.ts From hotseat-api with MIT License | 6 votes |
public async create(user_id: string): Promise<RecoverPasswordRequest> {
const recoverPasswordRequest = await this.ormRepository.create({
user_id,
expires_at: addHours(Date.now(), RESET_PASSWORD_REQUEST_EXPIRES_IN_HOURS),
});
await this.ormRepository.save(recoverPasswordRequest);
return recoverPasswordRequest;
}
Example #8
Source File: FakeRecoverPasswordRequestsRepository.ts From hotseat-api with MIT License | 6 votes |
public async create(user_id: string): Promise<RecoverPasswordRequest> {
const recoverPasswordRequest = Object.assign(new RecoverPasswordRequest(), {
user_id,
token: uuid(),
expires_at: addHours(Date.now(), RESET_PASSWORD_REQUEST_EXPIRES_IN_HOURS),
created_at: new Date(),
updated_at: new Date(),
});
this.requests.push(recoverPasswordRequest);
return recoverPasswordRequest;
}
Example #9
Source File: SendRecoverPasswordRequestMailService.spec.ts From hotseat-api with MIT License | 5 votes |
describe('Send Recover Password Mail', () => {
beforeEach(() => {
queueProvider = new FakeQueueProvider();
recoverPasswordRequestRepository = new FakeRecoverPasswordRequestsRepository();
usersRepository = new FakeUsersRepository();
sendRecoverPasswordMailService = new SendRecoverPasswordRequestMailService(
queueProvider,
usersRepository,
recoverPasswordRequestRepository,
);
});
it('should be able to send recover password request email', async () => {
const userData = {
name: 'Jackie Chan',
email: '[email protected]',
password: 'meaningless password',
};
const { email } = await usersRepository.create(userData);
const sendMail = jest.spyOn(queueProvider, 'processJob');
await sendRecoverPasswordMailService.execute({ email });
expect(sendMail).toHaveBeenCalled();
});
it('should not be able to send mails to nonexisting users', async () => {
await expect(
sendRecoverPasswordMailService.execute({
email: '[email protected]',
}),
).rejects.toBeInstanceOf(AppError);
});
it('should be able to create a token based on the user id', async () => {
const { id, email } = await usersRepository.create({
name: 'Jackie Chan',
email: '[email protected]',
password: 'meaningless password',
});
const createToken = jest.spyOn(recoverPasswordRequestRepository, 'create');
await sendRecoverPasswordMailService.execute({ email });
expect(createToken).toHaveBeenCalledWith(id);
});
it('should be able to create a expire date of two hours', async () => {
const { id } = await usersRepository.create({
name: 'Jackie Chan',
email: '[email protected]',
password: 'meaningless password',
});
const now = Date.now();
jest.spyOn(Date, 'now').mockImplementationOnce(() => now);
const request = await recoverPasswordRequestRepository.create(id);
expect(request?.expires_at).toEqual(
addHours(now, RESET_PASSWORD_REQUEST_EXPIRES_IN_HOURS),
);
});
});
Example #10
Source File: dateUtils.ts From ant-extensions with MIT License | 5 votes |
parseDate = (dt?: string, rounded?: "start" | "end"): ParsedDate => {
if (dt && isDate(dt)) {
return parseISO(dt);
} else if (dt && isDateLike(dt)) {
const parts = getDateParts(dt);
if (parts) {
const { part, op, diff } = parts;
const diffNum = parseInt(`${op}${diff}`, 10);
let date = startOfMinute(new Date());
switch (part) {
case DateParts.NOW:
return date;
case DateParts.DECADE:
if (rounded) {
date = (rounded === "start" ? startOfDecade : endOfDecade)(date);
}
return addYears(date, diffNum * 10);
case DateParts.YEAR:
if (rounded) {
date = (rounded === "start" ? startOfYear : endOfYear)(date);
}
return addYears(date, diffNum);
case DateParts.QUARTER:
if (rounded) {
date = (rounded === "start" ? startOfQuarter : endOfQuarter)(date);
}
return addQuarters(date, diffNum);
case DateParts.MONTH:
if (rounded) {
date = (rounded === "start" ? startOfMonth : endOfMonth)(date);
}
return addMonths(date, diffNum);
case DateParts.WEEK:
if (rounded) {
date = (rounded === "start" ? startOfWeek : endOfWeek)(date);
}
return addWeeks(date, diffNum);
case DateParts.DAY:
if (rounded) {
date = (rounded === "start" ? startOfDay : endOfDay)(date);
}
return addDays(date, diffNum);
case DateParts.HOUR:
if (rounded) {
date = (rounded === "start" ? startOfHour : endOfHour)(date);
}
return addHours(date, diffNum);
case DateParts.MINUTE:
if (rounded) {
date = (rounded === "start" ? startOfMinute : endOfMinute)(date);
}
return addMinutes(date, diffNum);
}
}
}
return undefined;
}
Example #11
Source File: dnd.ts From apps with GNU Affero General Public License v3.0 | 5 votes |
dndOption: { [K in TimeFormat]: DndOption<K> } = {
HALF_HOUR: {
value: 30,
label: '30 minutes',
getExpiration(): Date {
return addMinutes(new Date(), this.value);
},
},
ONE_HOUR: {
value: 1,
label: '1 hour',
getExpiration(): Date {
return addHours(new Date(), this.value);
},
},
TWO_HOURS: {
value: 2,
label: '2 hours',
getExpiration(): Date {
return addHours(new Date(), this.value);
},
},
TOMORROW: {
value: 1,
label: 'Tomorrow',
getExpiration(): Date {
return addDays(new Date(), this.value);
},
},
CUSTOM: {
value: 0,
label: 'Custom...',
getExpiration(time: CustomTime, value: number): Date {
const exp = new Date();
if (time === CustomTime.DAYS) return addDays(exp, value);
if (time === CustomTime.HOURS) return addHours(exp, value);
return addMinutes(exp, value);
},
},
}
Example #12
Source File: SleepChart.tsx From nyxo-app with GNU General Public License v3.0 | 5 votes |
SleepTimeChart: FC = () => {
const data = useAppSelector(getNightsAsDays)
const daysToShow = data.length
const chartWidth = (barWidth + 10) * daysToShow + paddingLeft + paddingRight
const xDomain: Date[] = extent(data, (date) => new Date(date.date)) as Date[]
const yDomain: number[] = [
min(data, (date) =>
min(date.night, (night) =>
subHours(new Date(night.startDate), 1).valueOf()
)
) as number,
max(data, (date) =>
max(date.night, (night) => addHours(new Date(night.endDate), 1).valueOf())
) as number
]
const scaleX = scaleTime()
.domain(xDomain)
.range([paddingLeft, chartWidth - paddingRight])
const scaleY = scaleTime()
.domain(yDomain)
.nice()
.range([10, chartHeight - 80])
const yTicks = scaleY.ticks(5)
const xTicks = scaleX.ticks(daysToShow)
return (
<Card>
<Title>STAT.TREND</Title>
<ScrollContainer>
<YTicksContainer
pointerEvents="auto"
width={chartWidth}
height={chartHeight}>
<YTicks scaleY={scaleY} chartWidth={chartWidth} ticks={yTicks} />
</YTicksContainer>
<ScrollView
style={{ transform: [{ scaleX: -1 }] }}
horizontal
showsHorizontalScrollIndicator={false}>
<View style={{ transform: [{ scaleX: -1 }] }}>
<Svg width={chartWidth} height={chartHeight}>
{/* <TargetBars
start={bedtimeWindow}
onPress={select}
barWidth={barWidth}
scaleX={scaleX}
scaleY={scaleY}
data={normalizedSleepData}
/> */}
<SleepBars
onPress={() => undefined}
barWidth={barWidth}
scaleX={scaleX}
scaleY={scaleY}
data={data}
/>
<XTicks
chartHeight={chartHeight}
scaleX={scaleX}
barWidth={barWidth}
ticks={xTicks}
/>
</Svg>
</View>
</ScrollView>
</ScrollContainer>
</Card>
)
}
Example #13
Source File: TargetBars.tsx From nyxo-app with GNU General Public License v3.0 | 5 votes |
TargetBars: FC<Props> = ({
data,
scaleX,
scaleY,
barWidth,
onPress,
start
}) => {
const end = addHours(new Date(start ?? new Date()), 8)
const { bars } = useMemo(
() => ({
bars: data.map((datum) => {
const y = scaleY(new Date(start ?? new Date()).valueOf())
const x = scaleX(new Date(datum.date))
const height =
scaleY(end.valueOf()) -
scaleY(new Date(start ?? new Date()).valueOf())
if (Number.isNaN(y)) return null
return (
<G onPress={() => onPress(datum)} key={datum.date}>
<Rect
x={x}
width={barWidth}
fillOpacity={0.1}
rx={5}
y={y}
height={height}
fill={colors.darkBlue}
/>
</G>
)
})
}),
[barWidth, data, end, onPress, scaleX, scaleY, start]
)
if (!start && typeof start !== 'string') return null
return <G>{bars}</G>
}
Example #14
Source File: sleep-data-helper.ts From nyxo-app with GNU General Public License v3.0 | 5 votes |
// Used to match sleep samples to date
export function matchDayAndNight(night: string, day: string): boolean {
const nightTime = new Date(night)
const nightStart = subHours(startOfDay(new Date(day)), 12)
const nightEnd = addHours(startOfDay(new Date(day)), 12)
return isWithinInterval(nightTime, { start: nightStart, end: nightEnd })
}
Example #15
Source File: SleepChart.tsx From nyxo-website with MIT License | 5 votes |
export function matchDayAndNight(night: string, day: string): boolean {
const nightTime = new Date(night)
const nightStart = subHours(startOfDay(new Date(day)), 12)
const nightEnd = addHours(startOfDay(new Date(day)), 12)
return isWithinInterval(nightTime, { start: nightStart, end: nightEnd })
}
Example #16
Source File: SleepChart.tsx From nyxo-website with MIT License | 5 votes |
SleepChart: FC<ChartProps> = ({ data }) => {
const ref = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
ref.current?.scrollBy({ left: ref.current.offsetWidth })
}, [])
const { normalizedData } = useMemo(
() => ({
normalizedData: getNightAsDays(data),
}),
[data]
)
const daysToShow = normalizedData.length
const chartWidth = (barWidth + 10) * daysToShow + paddingLeft + paddingRight
const xDomain: Date[] = extent(
normalizedData,
(date) => new Date(date.date)
) as Date[]
const yDomain: number[] = [
min(normalizedData, (date) =>
min(date.night, (night) =>
subHours(new Date(night.startDate), 1).valueOf()
)
) as number,
max(normalizedData, (date) =>
max(date.night, (night) => addHours(new Date(night.endDate), 1).valueOf())
) as number,
]
const scaleX = scaleTime()
.domain(xDomain)
.range([paddingLeft, chartWidth - paddingRight])
const scaleY = scaleTime()
.domain(yDomain)
.nice()
.range([10, chartHeight - 80])
const yTicks = scaleY.ticks(10)
const xTicks = scaleX.ticks(daysToShow)
return (
<Container ref={ref}>
<svg width={chartWidth} height={chartHeight}>
<XTicks
chartHeight={chartHeight}
scaleX={scaleX}
barWidth={barWidth}
ticks={xTicks}
/>
<SleepBars
barWidth={barWidth}
scaleX={scaleX}
scaleY={scaleY}
data={normalizedData}
/>
<YTicks scaleY={scaleY} chartWidth={chartWidth} ticks={yTicks} />
</svg>
</Container>
)
}
Example #17
Source File: quickShortcuts.ts From TidGi-Desktop with Mozilla Public License 2.0 | 5 votes |
quickShortcuts = [
{
name: '15 minutes',
calcDate: () => addMinutes(new Date(), 15),
},
{
name: '30 minutes',
calcDate: () => addMinutes(new Date(), 30),
},
{
name: '45 minutes',
calcDate: () => addMinutes(new Date(), 45),
},
{
name: '1 hour',
calcDate: () => addHours(new Date(), 1),
},
{
name: '2 hours',
calcDate: () => addHours(new Date(), 2),
},
{
name: '4 hours',
calcDate: () => addHours(new Date(), 4),
},
{
name: '6 hours',
calcDate: () => addHours(new Date(), 6),
},
{
name: '8 hours',
calcDate: () => addHours(new Date(), 8),
},
{
name: '10 hours',
calcDate: () => addHours(new Date(), 8),
},
{
name: '12 hours',
calcDate: () => addHours(new Date(), 12),
},
{
name: 'Until tomorrow',
calcDate: () => addDays(new Date(), 1),
},
{
name: 'Until next week',
calcDate: () => addWeeks(new Date(), 1),
},
]
Example #18
Source File: date.ts From ngx-gantt with MIT License | 5 votes |
addHours(amount: number): GanttDate {
return new GanttDate(addHours(this.value, amount));
}
Example #19
Source File: gmt9am.ts From anchor-web-app with Apache License 2.0 | 5 votes |
export function gmt9am(timestamp: number) {
return addHours(
subMinutes(startOfDay(timestamp), new Date().getTimezoneOffset()),
9,
).getTime();
}
Example #20
Source File: ResetPasswordService.spec.ts From hotseat-api with MIT License | 4 votes |
describe('Reset User Password', () => {
beforeEach(() => {
usersRepository = new FakeUsersRepository();
recoverPasswordRequestsRepository = new FakeRecoverPasswordRequestsRepository();
hashProvider = new FakeBCryptHashProvider();
resetPasswordService = new ResetPasswordService(
recoverPasswordRequestsRepository,
usersRepository,
hashProvider,
);
});
it('should be able to reset the user password', async () => {
const { id } = await usersRepository.create({
name: 'Jackie Chan',
email: '[email protected]',
password: 'meaningless password',
});
const recoverPasswordRequest = await recoverPasswordRequestsRepository.create(
id,
);
const newPassword = 'meaningless new password';
const generateHash = jest.spyOn(hashProvider, 'generateHash');
await resetPasswordService.execute({
token: recoverPasswordRequest.token,
password: newPassword,
});
const updatedUser = await usersRepository.findById(id);
expect(updatedUser?.password).toBe(newPassword);
expect(generateHash).toBeCalledWith(updatedUser?.password);
});
it('should not be able to reset the password of an nonexisting request', async () => {
await expect(
resetPasswordService.execute({
password: 'new meaningless password',
token: 'non existing request token',
}),
).rejects.toBeInstanceOf(AppError);
});
it('should not be able to reset the password of an nonexisting user', async () => {
const { token } = await recoverPasswordRequestsRepository.create(
'non existing user id',
);
await expect(
resetPasswordService.execute({
password: 'new meaningless password',
token,
}),
).rejects.toBeInstanceOf(AppError);
});
it('should not be able to reset the password if the request is expired', async () => {
jest.spyOn(Date, 'now').mockImplementationOnce(() => {
return getMilliseconds(
addHours(Date.now(), RESET_PASSWORD_REQUEST_EXPIRES_IN_HOURS),
);
});
const user = await usersRepository.create({
name: 'Jackie Chan',
email: '[email protected]',
password: 'meaningless password',
});
const { token } = await recoverPasswordRequestsRepository.create(user.id);
await expect(
resetPasswordService.execute({
password: 'new meaningless password',
token,
}),
).rejects.toBeInstanceOf(AppError);
});
it('should delete recover password request after reseting the password', async () => {
const user = await usersRepository.create({
name: 'Jackie Chan',
email: '[email protected]',
password: 'meaningless password',
});
const { token } = await recoverPasswordRequestsRepository.create(user.id);
await resetPasswordService.execute({
token,
password: 'new meaningless password',
});
const checkIfRequestExists = await recoverPasswordRequestsRepository.findByToken(
token,
);
expect(checkIfRequestExists).toBeFalsy();
});
});
Example #21
Source File: AcceptTerms.tsx From atlas with GNU General Public License v3.0 | 4 votes |
AcceptTerms: React.FC<AcceptTermsProps> = ({ selectedType, formData }) => {
const { startDate, endDate, type } = formData
const totalDaysAndHours = getTotalDaysAndHours(startDate, endDate)
const isStartDateValid = startDate?.type === 'date'
const isEndDateValid = endDate?.type === 'date'
const isAuction = selectedType === 'Auction'
const durationBlocks = formData.auctionDurationBlocks || 0
const convertedEndData = !isEndDateValid
? addHours(isStartDateValid ? startDate.date : new Date(), endDate ? endDate.durationDays * 24 : 0)
: undefined
return (
<>
<Header variant="h500">Review listing terms</Header>
<Divider />
<Text variant="h400">Listing terms</Text>
<Row>
<Title>
<TitleText>Listing type</TitleText>
<StyledInformation
text={
isAuction
? 'Put it on a timed or open auction. See the bids coming.'
: 'Sell it for a fixed price only. No bids.'
}
placement="top"
/>
</Title>
<Description>
<DescriptionText>
{isAuction ? `${type === 'open' ? 'Open' : 'Timed'} auction` : selectedType}
</DescriptionText>
</Description>
</Row>
{formData.startingPrice && isAuction && (
<Row>
<Title>
<TitleText>Minimum bid</TitleText>
<StyledInformation text="Only bids higher than this value will be accepted" placement="top" />
</Title>
<Description>
<DescriptionText>{formatTokens(formData.startingPrice, true)}</DescriptionText>
</Description>
</Row>
)}
{formData?.buyNowPrice && (
<Row>
<Title>
<TitleText>{isAuction ? 'Buy now price' : 'Fixed price'}</TitleText>
<StyledInformation
text={
isAuction
? 'Bids matching this value will automatically end your auction'
: 'Price for your NFT as shown to your buyers'
}
placement="top"
/>
</Title>
<Description>
<DescriptionText>{formatTokens(formData.buyNowPrice, true)}</DescriptionText>
</Description>
</Row>
)}
{selectedType !== 'Fixed price' && (
<Row>
<Title>
<TitleText>Start date</TitleText>
<StyledInformation
text="The moment in time when your auction becomes active and bids will be accepted"
placement="top"
/>
</Title>
<Description>
<DescriptionText>{isStartDateValid ? formatDateTime(startDate.date) : 'Now'}</DescriptionText>
</Description>
</Row>
)}
{formData.endDate && (
<>
<Row>
<Title>
<TitleText>End date</TitleText>
<StyledInformation
text="The moment in time when your auction ends. It cannot be finished earlier."
placement="top"
/>
</Title>
<Description>
<DescriptionText>
{isEndDateValid ? formatDateTime(endDate.date) : convertedEndData && formatDateTime(convertedEndData)}
</DescriptionText>
</Description>
</Row>
{durationBlocks > 0 && (
<Row>
<Title>
<TitleText>Total auction duration</TitleText>
<StyledInformation text="On blockchain, duration is expressed in number of blocks" placement="top" />
</Title>
<Description>
<DescriptionText>{totalDaysAndHours}</DescriptionText>
<Text variant="h400" secondary>
/ {formatNumber(durationBlocks)} blocks
</Text>
</Description>
</Row>
)}
</>
)}
{(formData.whitelistedMembers || []).length > 0 && (
<WhiteListRow>
<Title>
<TitleText>Whitelist</TitleText>
<StyledInformation
text="Only members included in the whitelist will be able to bid on this auction"
placement="top"
/>
</Title>
<MembersList>
{formData.whitelistedMembers?.map((member) => (
<MemberWithResolvedAvatar key={member.id} member={member} />
))}
</MembersList>
</WhiteListRow>
)}
<Divider />
<Text variant="h400">Transaction</Text>
<Row>
<Title>
<TitleText>Fee</TitleText>
<StyledInformation text="Fee covers cost of blockchain computation of this transaction" placement="top" />
</Title>
<Description>
<DescriptionText>{formatTokens(0)}</DescriptionText>
</Description>
</Row>
</>
)
}