date-fns#parseISO TypeScript Examples
The following examples show how to use
date-fns#parseISO.
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: date.tsx From platyplus with MIT License | 6 votes |
DateField: FieldComponent = ({ document, name, edit, editable }) =>
edit && editable ? (
<FieldControl
name={name}
readOnly={!edit}
cleanable={edit}
format={UI_DATE_FORMAT}
date={true}
time={false}
accepter={DatePickerAccepter}
/>
) : document[name] ? (
<span>{format(parseISO(document[name]), UI_DATE_FORMAT_FNS)}</span>
) : null
Example #2
Source File: postList.tsx From jeffjadulco.com with MIT License | 6 votes |
function Post({ post }: { post: Frontmatter }) {
return (
<li className="py-5">
<Link href={`blog/${post.slug}`}>
<a className="flex flex-col px-8 py-5 -my-5 transition-colors ease-in-out -mx-7 group sm:flex-row sm:justify-between sm:items-end hover:bg-back-secondary focus:bg-back-secondary focus-visible:outline-accent focus:text-accent">
<div>
<h3 className="text-xl font-semibold group-hover:text-accent">
{post.title}
</h3>
<h4 className="font-medium text-fore-subtle">{post.description}</h4>
</div>
<div className="mt-2 text-sm sm:mt-0 sm:text-base text-accent sm:text-fore-subtle">
{format(parseISO(post.publishedAt), 'MMMM yyyy')}
</div>
</a>
</Link>
</li>
)
}
Example #3
Source File: time.ts From nyxo-app with GNU General Public License v3.0 | 6 votes |
getFormattedDateOrPlaceholder = (
value: string | null | undefined,
formatter: string
): string => {
if (value) {
return format(parseISO(value), formatter)
}
return '-'
}
Example #4
Source File: selectors.ts From jellyfin-audio-player with MIT License | 6 votes |
/**
* Retrieves a list of the n most recent albums
*/
export function useRecentAlbums(amount: number) {
const albums = useTypedSelector((state) => state.music.albums.entities);
const albumIds = useTypedSelector((state) => state.music.albums.ids);
const sorted = [...albumIds].sort((a, b) => {
const albumA = albums[a];
const albumB = albums[b];
const dateA = albumA ? parseISO(albumA.DateCreated).getTime() : 0;
const dateB = albumB ? parseISO(albumB.DateCreated).getTime() : 0;
return dateB - dateA;
});
return sorted.slice(0, amount);
}
Example #5
Source File: index.tsx From podcastr with MIT License | 6 votes |
getStaticProps: GetStaticProps = async () => {
const { data } = await api.get('episodes', {
params: {
_limit: 12,
_sort: 'published_at',
_order: 'desc'
}
});
const episodes = data.map(episode => {
return {
id: episode.id,
title: episode.title,
thumbnail: episode.thumbnail,
members: episode.members,
publishedAt: format(parseISO(episode.published_at), 'd MMM yy', { locale: ptBR }),
duration: Number(episode.file.duration),
durationAsString: convertDurationToTimeString(Number(episode.file.duration)),
url: episode.file.url
}
})
const latestEpisodes = episodes.slice(0, 2)
const allEpisodes = episodes.slice(2, episodes.length)
return {
props: {
latestEpisodes,
allEpisodes,
},
revalidate: 60 * 60 * 8,
}
}
Example #6
Source File: helpers.ts From glide-frontend with GNU General Public License v3.0 | 6 votes |
combineDateAndTime = (date: Date, time: Date) => {
if (!isValid(date) || !isValid(time)) {
return null
}
const dateStr = format(date, 'yyyy-MM-dd')
const timeStr = format(time, 'HH:mm:ss')
return parseISO(`${dateStr}T${timeStr}`).getTime() / 1e3
}
Example #7
Source File: UserBookings.tsx From office-booker with MIT License | 6 votes |
sortData = (data: Booking[], key: keyof Booking, order: SortOrder): Booking[] | undefined => {
if (key === 'office') {
return order === 'desc'
? data.sort((a, b) => b.office.name.localeCompare(a.office.name))
: data.sort((a, b) => a.office.name.localeCompare(b.office.name));
}
if (key === 'parking') {
return order === 'desc'
? data.sort((a, b) => Number(a.parking) - Number(b.parking))
: data.sort((a, b) => Number(b.parking) - Number(a.parking));
}
if (key === 'date') {
return order === 'desc'
? data.sort((a, b) => parseISO(a.date).valueOf() - parseISO(b.date).valueOf())
: data.sort((a, b) => parseISO(b.date).valueOf() - parseISO(a.date).valueOf());
}
return data;
}
Example #8
Source File: DocumentStepperStep.tsx From solo with MIT License | 6 votes |
Step: React.FC<StepProps> = ({
first = false,
last = false,
complete = false,
title,
occuredAt
}) => (
<div
className={classNames(classes.step, {
[classes.stepComplete]: complete,
[classes.stepIncomplete]: !complete
})}
>
<StatusIcon className={classes.stepIcon} complete={Boolean(complete)} />
<div>{title}</div>
{occuredAt && (
<div>{`${formatDistanceToNow(parseISO(occuredAt))} ago `}</div>
)}
{!first && <div className={classes.stepLeft} />}
{!last && <div className={classes.stepRight} />}
</div>
)
Example #9
Source File: cms.tsx From oxen-website with GNU General Public License v3.0 | 6 votes |
public convertPost = (rawData: any, taglist: ITagList): IPost => {
const rawPost = rawData.fields;
const rawFeatureImage = rawPost?.featureImage
? rawPost?.featureImage.fields
: null;
const rawAuthor = rawPost.author ? rawPost.author.fields : null;
return {
id: rawData.sys.id ?? null,
body: rawPost.body ?? null,
subtitle: rawPost.subtitle ?? null,
description: rawPost.description ?? null,
publishedDateISO: rawPost.date,
publishedDate: format(parseISO(rawPost.date), 'dd MMMM yyyy'),
slug: rawPost.slug,
tags: this.convertTags(rawData.metadata.tags, taglist),
title: rawPost.title,
featureImage: this.convertImage(rawFeatureImage),
author: this.convertAuthor(rawAuthor),
};
};
Example #10
Source File: date-time.tsx From platyplus with MIT License | 6 votes |
DateTimeField: FieldComponent = ({
document,
name,
edit,
editable
}) =>
edit && editable ? (
<FieldControl
name={name}
readOnly={!edit}
cleanable={edit}
format={UI_DATE_TIME_FORMAT}
date={true}
time={true}
accepter={DatePickerAccepter}
/>
) : document[name] ? (
<span>{format(parseISO(document[name]), UI_DATE_TIME_FORMAT_FNS)}</span>
) : null
Example #11
Source File: ngx-mat-datefns-date-adapter.ts From ngx-mat-datefns-date-adapter with MIT License | 6 votes |
deserialize(value: any): Date | null {
if (value) {
if (typeof value === 'string') {
if (this.options?.useUtc) {
return parseJSON(value);
}
return parseISO(value);
}
if (typeof value === 'number') {
return toDate(value);
}
if (value instanceof Date) {
return this.clone(value as Date);
}
return null;
}
return null;
}
Example #12
Source File: [post].tsx From nextjs-netlify-blog-template with MIT License | 6 votes |
export default function Post({
title,
dateString,
slug,
tags,
author,
description = "",
source,
}: Props) {
const content = hydrate(source, { components })
return (
<PostLayout
title={title}
date={parseISO(dateString)}
slug={slug}
tags={tags}
author={author}
description={description}
>
{content}
</PostLayout>
)
}
Example #13
Source File: github.ts From merged-pr-stat with MIT License | 6 votes |
export async function fetchAllMergedPullRequests(
searchQuery: string,
startDateString?: string,
endDateString?: string
): Promise<PullRequest[]> {
const startDate = startDateString ? parseISO(startDateString).toISOString() : "";
const endDate = endDateString ? parseISO(endDateString).toISOString() : "";
let q = `is:pr is:merged ${searchQuery}`;
if (startDate !== "" || endDate !== "") {
q += ` merged:${startDate}..${endDate}`;
}
return fetchAllPullRequestsByQuery(q);
}
Example #14
Source File: [slug].tsx From BloggerWeb with GNU General Public License v3.0 | 6 votes |
PostPage = ({ source, frontMatter }: PostPageProps): JSX.Element => {
const content = hydrate(source, { components });
const customMeta: MetaProps = {
title: `${frontMatter.title} - Hunter Chang`,
description: frontMatter.description,
image: `${WEBSITE_HOST_URL}${frontMatter.image}`,
date: frontMatter.date,
type: 'article',
};
return (
<Layout customMeta={customMeta}>
<article>
<h1 className="mb-3 text-gray-900 dark:text-white">
{frontMatter.title}
</h1>
<p className="mb-10 text-sm text-gray-500 dark:text-gray-400">
{format(parseISO(frontMatter.date), 'MMMM dd, yyyy')}
</p>
<div className="prose dark:prose-dark">{content}</div>
</article>
</Layout>
);
}
Example #15
Source File: make-stat-on-interval-days-basis.ts From merged-pr-stat with MIT License | 6 votes |
async function main(): Promise<void> {
program
.requiredOption("--start <date>")
.requiredOption("--end <date>")
.requiredOption("--interval-days <days>")
.requiredOption("--query <query>");
program.parse(process.argv);
const startDate = parseISO(program.start);
const endDate = parseISO(program.end);
const query = program.query as string;
const intervalDays = parseInt(program.intervalDays);
const allStats = [];
for (let start = startDate; start < endDate; start = addDays(start, intervalDays)) {
const end = add(start, { days: intervalDays, seconds: -1 });
console.error(format(start, "yyyy-MM-dd HH:mm:ss"));
console.error(format(end, "yyyy-MM-dd HH:mm:ss"));
const stdout = execFileSync(
"merged-pr-stat",
["--start", start.toISOString(), "--end", end.toISOString(), "--query", query],
{ encoding: "utf8" }
);
const result = {
startDate: format(start, "yyyy-MM-dd HH:mm:ss"),
endDate: format(end, "yyyy-MM-dd HH:mm:ss"),
...JSON.parse(stdout),
};
allStats.push(result);
}
process.stdout.write(csvStringify(allStats, { header: true }));
}
Example #16
Source File: dateUtils.ts From ant-extensions with MIT License | 6 votes |
parseLabel = (dt: string): string => {
if (isDate(dt)) {
return format(parseISO(dt), "PP");
} else if (isDateLike(dt)) {
const parts = getDateParts(dt);
if (parts) {
let retVal;
const { part, op, diff } = parts;
const count = parseInt(`${op}${diff}`, 10);
const t = (k: string, o?: KeyValue) => i18n.t(`${I18nKey}:${k}`, o);
if (part === DateParts.NOW) {
retVal = t(`label.${DateParts.NOW}`);
} else if (count === 0) {
retVal = t(`now.${part}`);
} else {
retVal = t(`${count < 0 ? "prev" : "next"}.${part}`, { count: Math.abs(count) });
}
return retVal;
}
}
return "";
}
Example #17
Source File: make-rotate-stat-on-interval-days-basis.ts From merged-pr-stat with MIT License | 6 votes |
// Make stat between (<date> - <aggregationDays>) and <date>
// and move aggregation period by <intervalDays>.
async function main(): Promise<void> {
program
.requiredOption("--start <date>")
.requiredOption("--end <date>")
.requiredOption("--interval-days <days>")
.requiredOption("--aggregation-days <days>")
.requiredOption("--query <query>");
program.parse(process.argv);
const startDate = parseISO(program.start);
const endDate = parseISO(program.end);
const query = program.query as string;
const intervalDays = parseInt(program.intervalDays);
const aggregationDays = parseInt(program.aggregationDays);
const allStats = [];
for (let start = startDate; start < endDate; start = addDays(start, intervalDays)) {
const aggregateFrom = add(start, { days: -aggregationDays });
const aggregateTo = start;
console.error(format(aggregateFrom, "yyyy-MM-dd HH:mm:ss"));
console.error(format(aggregateTo, "yyyy-MM-dd HH:mm:ss"));
const stdout = execFileSync(
"merged-pr-stat",
["--start", aggregateFrom.toISOString(), "--end", aggregateTo.toISOString(), "--query", query],
{ encoding: "utf8" }
);
const result = {
startDate: format(aggregateFrom, "yyyy-MM-dd HH:mm:ss"),
endDate: format(aggregateTo, "yyyy-MM-dd HH:mm:ss"),
...JSON.parse(stdout),
};
allStats.push(result);
}
process.stdout.write(csvStringify(allStats, { header: true }));
}
Example #18
Source File: columns.tsx From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
createColumns: CreateColumns = () => [
{
Header: 'Details',
Cell: ({ row: { original } }: CellProps<Domain>) => (
<Link to={`/inventory/domain/${original.id}`}>
<FaSearch className="margin-x-auto display-block" />
</Link>
)
},
{
Header: 'Organization',
accessor: (e) => e.organization.name,
id: 'organizationName',
Filter: ColumnFilter
},
{
Header: 'Domain',
accessor: 'name',
id: 'reverseName',
Filter: ColumnFilter
},
{
Header: 'IP',
accessor: 'ip',
Filter: ColumnFilter
},
{
Header: 'Ports',
id: 'port',
disableSortBy: true,
accessor: ({ services }) =>
services.map((service) => service.port).join(', '),
Filter: ColumnFilter
},
{
Header: 'Services',
id: 'service',
disableSortBy: true,
accessor: (domain) => getServiceNames(domain),
Filter: ColumnFilter
},
{
Header: 'Vulnerabilities',
id: 'vulnerability',
accessor: (domain) =>
domain.vulnerabilities &&
domain.vulnerabilities
.map((vulnerability) => vulnerability.cve)
.join(', '),
Filter: ColumnFilter
},
{
Header: 'Last Seen',
id: 'updatedAt',
accessor: ({ updatedAt }) =>
`${formatDistanceToNow(parseISO(updatedAt))} ago`,
disableFilters: true
},
{
Header: 'First Seen',
id: 'createdAt',
accessor: ({ createdAt }) =>
`${formatDistanceToNow(parseISO(createdAt))} ago`,
disableFilters: true
}
]
Example #19
Source File: model.ts From office-booker with MIT License | 5 votes |
getBookingAdminLastCancelTime = (date: string) =>
endOfDay(parseISO(date)).toISOString()
Example #20
Source File: task.ts From command-bot with Apache License 2.0 | 5 votes |
parseTaskQueuedDate = (str: string) => {
return parseISO(str)
}
Example #21
Source File: index.ts From integration-services with Apache License 2.0 | 5 votes |
getDateFromString = (dateString: string): Date | undefined => {
return dateString ? parseISO(dateString) : undefined;
}
Example #22
Source File: index.tsx From vignette-web with MIT License | 5 votes |
function PostCard(post: Post) {
return (
<div className="mb-6 w-full md:max-w-[22.5rem] ">
<Link href={post.url} passHref>
<a className="inline-flex h-44 overflow-hidden rounded xs:h-64 lg:h-48 ">
<Image
src={post.image}
width="1080"
height="810"
quality={100}
className="rounded object-cover object-center"
alt=""
/>
</a>
</Link>
<div className="w-full py-4 ">
<h3 className="my-1 text-xs font-bold uppercase text-pinkRed">
{post.category}
</h3>
<Link href={post.url} passHref>
<a>
<h2 className="text-2xl font-bold ">{post.title}</h2>
<p className="mt-4">{post.summary}</p>
</a>
</Link>
<div className="mt-4 flex items-center">
<Link
href={members.filter((item) => item.name == post.author)[0].url}
>
<a>
<Image
src={
members.filter((item) => item.name == post.author)[0].avatar
}
width={40}
height={40}
alt=""
className="rounded-full"
/>
</a>
</Link>
<div className="pl-2 text-sm">
<Link
href={members.filter((item) => item.name == post.author)[0].url}
>
<a>
<span className="font-semibold">{post.author}</span>
</a>
</Link>
<time
dateTime={post.date}
className="block text-gray-600 dark:text-gray-200"
>
{format(parseISO(post.date), `LLLL d, yyyy`)}
</time>
</div>
</div>
</div>
</div>
)
}
Example #23
Source File: make-long-term-log.ts From merged-pr-stat with MIT License | 5 votes |
async function main(): Promise<void> {
program.requiredOption("--start <date>").requiredOption("--end <date>").requiredOption("--query <query>");
program.parse(process.argv);
const startDate = parseISO(program.start);
const endDate = parseISO(program.end);
const query = program.query as string;
const intervalDays = 7;
const allLogs = [];
process.stdout.write(
"title,author,url,createdAt,mergedAt,additions,deletions,authoredDate,leadTimeSeconds,timeToMergeSeconds\n"
);
for (let start = startDate; start < endDate; start = addDays(start, intervalDays)) {
const end = min([add(start, { days: intervalDays, seconds: -1 }), endDate]);
console.error(format(start, "yyyy-MM-dd HH:mm:ss"));
console.error(format(end, "yyyy-MM-dd HH:mm:ss"));
const stdout = execFileSync(
"merged-pr-stat",
["log", "--start", start.toISOString(), "--end", end.toISOString(), "--query", query],
{ encoding: "utf8" }
);
const logs: any[] = JSON.parse(stdout);
process.stdout.write(
csvStringify(
logs.map((l) => [
l.title,
l.author,
l.url,
l.createdAt,
l.mergedAt,
l.additions,
l.deletions,
l.authoredDate,
l.leadTimeSeconds,
l.timeToMergeSeconds,
])
)
);
}
}
Example #24
Source File: [slug].tsx From jeffjadulco.com with MIT License | 5 votes |
export default function BlogPost({
post: { code, frontmatter },
}: InferGetStaticPropsType<typeof getStaticProps>) {
const Component = useMemo(() => getMDXComponent(code), [code])
const publishedAt = parseISO(frontmatter.publishedAt)
const updatedAt = frontmatter.updatedAt
? parseISO(frontmatter.updatedAt)
: undefined
return (
<Fragment>
<SEO
blog
title={frontmatter.title}
description={frontmatter.description}
ogImage={frontmatter.seoImage}
/>
<div
className={classNames(
'relative flex justify-between mt-12 mb-12 xl:-mr-52',
{
'flex-row-reverse': Boolean(frontmatter.toc),
}
)}
>
{frontmatter.toc && (
<aside className="sticky hidden h-screen max-w-xs mt-8 ml-6 top-16 xl:block">
<QuickNav />
</aside>
)}
<article className="max-w-3xl min-w-0 text-base lg:text-lg text-fore-subtle">
<div className="mb-2 text-sm tracking-normal text-fore-subtle">
<span>
<time dateTime={publishedAt.toISOString()}>
{format(publishedAt, 'MMMM dd yyyy')}
</time>
</span>
<span> • </span>
<span>{frontmatter.readingTime.text}</span>
{updatedAt && (
<Fragment>
<span> • </span>
<span className="italic">
Last updated:{' '}
<time dateTime={updatedAt.toISOString()}>
{format(updatedAt, 'MMMM dd yyyy')}
</time>
</span>
</Fragment>
)}
</div>
<h1 className="mb-10 text-4xl font-extrabold lg:text-5xl text-fore-primary">
{frontmatter.title}
</h1>
<Component components={components} />
</article>
</div>
<Feedback post={frontmatter} />
</Fragment>
)
}
Example #25
Source File: DonorsAndDonations.tsx From frontend with MIT License | 5 votes |
export default function DonorsAndDonations({
donations,
}: {
donations: CampaignDonation[] | undefined
}) {
const { t, i18n } = useTranslation()
const [all, setAll] = useState<boolean>(false)
const shownDonationsNumber = 5
const donationsToShow = useMemo(() => {
if (all) {
return donations
}
return donations?.slice(0, shownDonationsNumber)
}, [donations, all])
return (
<Root>
<Grid item className={classes.donationsWrapper}>
{donationsToShow && donationsToShow.length !== 0 ? (
donationsToShow.map(({ person, amount, createdAt }, key) => (
<Grid key={key} className={classes.donationItemWrapper}>
<AccountCircleIcon fontSize="large" color="disabled" />
<Grid>
<Typography>
{t('campaigns:cta.donor')} {key + 1}.{' '}
{person
? person.firstName + ' ' + person.lastName
: t('campaigns:donations.anonymous')}
</Typography>
<Grid className={classes.donationQuantityAndTimeWrapper}>
<Typography>
{(amount / 100).toFixed(2) + ' ' + t('campaigns:donations.lv')}
</Typography>
<FiberManualRecordIcon className={classes.separatorIcon} />
<Typography>
{formatRelative(parseISO(createdAt), new Date(), {
locale: i18n.language == 'bg' ? bg : enUS,
})}
</Typography>
</Grid>
</Grid>
</Grid>
))
) : (
<Typography sx={{ textAlign: 'center', marginBottom: theme.spacing(4) }}>
{t('campaigns:donations.none')}
</Typography>
)}
</Grid>
<Grid>
{donations && donations.length > shownDonationsNumber && (
<Button onClick={() => setAll((prev) => !prev)} variant="outlined">
{all ? t('campaigns:cta.see-less') : t('campaigns:cta.see-all')}
</Button>
)}
</Grid>
</Root>
)
}
Example #26
Source File: cache.ts From atlas with GNU General Public License v3.0 | 5 votes |
createDateHandler = () => ({
merge: (_: unknown, existingData: string | Date): Date => {
if (typeof existingData !== 'string') {
return existingData
}
return parseISO(existingData)
},
})
Example #27
Source File: ScanTasksView.tsx From crossfeed with Creative Commons Zero v1.0 Universal | 5 votes |
dateAccessor = (date?: string) => {
return !date || new Date(date).getTime() === new Date(0).getTime()
? 'None'
: `${formatDistanceToNow(parseISO(date))} ago`;
}
Example #28
Source File: hooks.ts From atlas with GNU General Public License v3.0 | 5 votes |
useVideoWorkspaceData = () => {
const { editedVideoInfo } = useVideoWorkspace()
const { activeChannelId } = useAuthorizedUser()
const drafts = useDraftStore(channelDraftsSelector(activeChannelId))
const { video, loading, error } = useVideo(editedVideoInfo?.id ?? '', {
skip: editedVideoInfo?.isDraft,
onError: (error) => SentryLogger.error('Failed to fetch video', 'useVideoWorkspaceData', error),
})
if (!editedVideoInfo) {
return {
tabData: null,
loading: false,
error: null,
}
}
const draft = drafts.find((d) => d.id === editedVideoInfo.id)
const assets: VideoWorkspaceVideoAssets = editedVideoInfo.isDraft
? {
video: {
id: null,
},
thumbnail: {
cropId: null,
originalId: null,
},
}
: {
video: {
id: video?.media?.id ?? null,
},
thumbnail: {
cropId: video?.thumbnailPhoto?.id ?? null,
originalId: null,
},
}
const normalizedData: VideoWorkspaceVideoFormFields = {
title: editedVideoInfo.isDraft ? draft?.title ?? '' : video?.title ?? '',
description: (editedVideoInfo.isDraft ? draft?.description : video?.description) ?? '',
category: (editedVideoInfo.isDraft ? draft?.category : video?.category?.id) ?? null,
licenseCode: (editedVideoInfo.isDraft ? draft?.licenseCode : video?.license?.code) ?? DEFAULT_LICENSE_ID,
licenseCustomText: (editedVideoInfo.isDraft ? draft?.licenseCustomText : video?.license?.customText) ?? null,
licenseAttribution: (editedVideoInfo.isDraft ? draft?.licenseAttribution : video?.license?.attribution) ?? null,
language: (editedVideoInfo.isDraft ? draft?.language : video?.language?.iso) ?? 'en',
isPublic: (editedVideoInfo.isDraft ? draft?.isPublic : video?.isPublic) ?? true,
isExplicit: (editedVideoInfo.isDraft ? draft?.isExplicit : video?.isExplicit) ?? false,
hasMarketing: (editedVideoInfo.isDraft ? draft?.hasMarketing : video?.hasMarketing) ?? false,
publishedBeforeJoystream:
(editedVideoInfo.isDraft
? draft?.publishedBeforeJoystream
? parseISO(draft.publishedBeforeJoystream)
: null
: video?.publishedBeforeJoystream) ?? null,
assets,
mintNft: !!video?.nft,
nftRoyaltiesPercent: video?.nft?.creatorRoyalty || undefined,
}
return {
tabData: normalizedData,
loading: editedVideoInfo.isDraft ? false : loading,
error,
}
}
Example #29
Source File: ListProviderAppointmentsService.ts From hotseat-api with MIT License | 5 votes |
async execute({
day,
year,
month,
provider_id,
}: IRequest): Promise<IResponse[]> {
const appointmentsListCacheKey = getProviderAppointmentsListCacheKey(
provider_id,
new Date(year, parseMonthToJSMonth(month), day),
);
let appointments = await this.cacheProvider.get<Appointment[]>(
appointmentsListCacheKey,
);
if (!appointments) {
appointments = await this.appointmentsRepository.findByDayFromProvider({
day,
year,
month,
provider_id,
});
await this.cacheProvider.save<Appointment[]>(
appointmentsListCacheKey,
classToClass(appointments),
);
}
const listAppointments = appointments.map(appointment => {
const currentDate = new Date(Date.now());
const parseCachedDate =
typeof appointment.date === 'string'
? parseISO(appointment.date)
: appointment.date;
return {
...appointment,
isPast: isBefore(parseCachedDate, currentDate),
};
});
return listAppointments;
}