Skip to content

Formatting dates

Use the formatDate function in /src/lib/utils.ts to format dates. The default locale is set to en-US — you can change this in /src/siteConfig.ts.

import { formatDate } from "@/lib/util";
// Returns "8/8/2024" in "en-US" locale.
formatDate(new Date());
// Returns "2024-08-02" in "en-CA" locale.
formatDate(entry.data.publicationDate, {}, "en-CA");
// Returns "August 8, 2024" in "en-US" locale.
formatDate(new Date(), {
year: "numeric",
month: "long",
day: "numeric",
});
// Returns "8/2/24" in "en-US" locale.
formatDate(entry.data.publicationDate, {
year: "2-digit",
});

Adding timestamps

For a more detailed timestamp, you use ISO 8601 format. This will improve how your RSS feed is displayed in readers, and will also ensure that posts published on the same day are sorted correctly.

src/content/posts/my-first-post/index.md
---
publicationDate: 2024-08-27T02:29:52.695Z
---

Displaying the timestamp

  1. Update the formatDate function in /src/lib/utils.ts.

    src/lib/utils.ts
    import { SITE } from "@/siteConfig.ts";
    export function formatDate(
    date: Date,
    options: {
    year?: "numeric" | "2-digit";
    month?: "numeric" | "2-digit" | "long" | "short" | "narrow";
    day?: "numeric" | "2-digit";
    hour?: "numeric" | "2-digit";
    minute?: "numeric" | "2-digit";
    timezone?: string;
    } = {},
    locale: string = SITE.locale,
    ): string {
    const defaultOptions: Intl.DateTimeFormatOptions = {
    year: "numeric",
    month: "numeric",
    day: "numeric",
    hour: undefined,
    minute: undefined,
    timeZone: SITE.timezone,
    ...options,
    };
    const formatOptions = { ...defaultOptions, ...options };
    return new Intl.DateTimeFormat(locale, formatOptions).format(date);
    }
  2. Update src/types.ts to include the new timezone property.

    src/types.ts
    export type SiteConfiguration = {
    title: string;
    description: string;
    url: string;
    author: string;
    locale: string;
    timezone: string;
    };
  3. Add the timezone property to your siteConfig.ts file.

    src/siteConfig.ts
    export const SITE = {
    title: "My Site",
    description: "My Site Description",
    url: "https://example.com",
    author: "My Name",
    locale: "en-US",
    timezone: "America/Vancouver",
    };
  4. Display the timestamp on your page.

    src/pages/blog/[...slug].astro
    ---
    import { formatDate } from "@/lib/utils.ts";
    ---
    <time>
    {
    formatDate(entry.data.publicationDate, {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    })
    }
    </time>