1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-07-03 17:26:37 -04:00

dayjs ➡️ date-fns

This commit is contained in:
2025-03-21 13:20:42 -04:00
parent 9fd3de8569
commit 8890c1d08d
9 changed files with 57 additions and 60 deletions

View File

@ -1,24 +1,31 @@
"use client";
import { useHasMounted } from "../../hooks";
import { formatDate, formatTimeAgo } from "../../lib/helpers/format-date";
import { format, formatISO, formatDistanceToNowStrict } from "date-fns";
import { enUS } from "date-fns/locale";
import { tz } from "@date-fns/tz";
import { utc } from "@date-fns/utc";
import * as config from "../../lib/config";
import type { ComponentPropsWithoutRef } from "react";
export type RelativeTimeProps = ComponentPropsWithoutRef<"time"> & {
date: string | number | Date;
verb?: string; // optional "Updated", "Published", "Created", etc.
staticFormat?: string; // format for the placeholder/fallback before client-side renders the relative time
date: string;
};
const RelativeTime = ({ date, verb, staticFormat, ...rest }: RelativeTimeProps) => {
const RelativeTime = ({ date, ...rest }: RelativeTimeProps) => {
// play nice with SSR -- only use relative time on the client, since it'll quickly become outdated on the server and
// cause a react hydration mismatch error.
const hasMounted = useHasMounted();
return (
<time dateTime={formatDate(date)} title={formatDate(date, "MMM D, YYYY, h:mm A z")} {...rest}>
{verb && `${verb} `}
{hasMounted ? formatTimeAgo(date, { suffix: true }) : `on ${formatDate(date, staticFormat)}`}
<time
dateTime={formatISO(date, { in: utc })}
title={format(date, "MMM d, y, h:mm a O", { in: tz(config.timeZone), locale: enUS })}
{...rest}
>
{hasMounted
? formatDistanceToNowStrict(date, { locale: enUS, addSuffix: true })
: `on ${format(date, "MMM d, y", { in: tz(config.timeZone), locale: enUS })}`}
</time>
);
};

View File

@ -1,15 +1,23 @@
import { formatDate } from "../../lib/helpers/format-date";
import { format, formatISO } from "date-fns";
import { enUS } from "date-fns/locale";
import { tz } from "@date-fns/tz";
import { utc } from "@date-fns/utc";
import * as config from "../../lib/config";
import type { ComponentPropsWithoutRef } from "react";
export type TimeProps = ComponentPropsWithoutRef<"time"> & {
date: string | number | Date;
date: string;
format?: string;
};
const Time = ({ date, format = "MMM D", ...rest }: TimeProps) => {
const Time = ({ date, format: formatStr = "PPpp", ...rest }: TimeProps) => {
return (
<time dateTime={formatDate(date)} title={formatDate(date, "MMM D, YYYY, h:mm A z")} {...rest}>
{formatDate(date, format)}
<time
dateTime={formatISO(date, { in: utc })}
title={format(date, "MMM d, y, h:mm a O", { in: tz(config.timeZone), locale: enUS })}
{...rest}
>
{format(date, formatStr, { in: tz(config.timeZone), locale: enUS })}
</time>
);
};