Skip to content

Commit

Permalink
js: format date
Browse files Browse the repository at this point in the history
  • Loading branch information
gorenburg committed Jan 10, 2025
1 parent 45d07e4 commit 5024c5e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
24 changes: 21 additions & 3 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
type DateStyle = Intl.DateTimeFormatOptions['dateStyle']

export function formatDate(date: string, dateStyle: DateStyle = 'long', locales = 'en-US') {
const dateToFormat = new Date(date.replace(/ /, 'T').replace(/ /, ''))
return new Intl.DateTimeFormat(locales, { dateStyle }).format(dateToFormat)
const timePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})\s(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})\s(?<timezone>[+-]\d{4})/;

export function formatDate(date: string, dateStyle: DateStyle = 'long', locales = 'en-US'): string {
const match = date.match(timePattern)

if (match) {
const { groups } = match
const components = {
year: groups?.year,
month: groups?.month,
day: groups?.day,
hour: groups?.hour,
minute: groups?.minute,
second: groups?.second,
timezone: groups?.timezone
}
const dateToFormat = new Date(`${components.year}-${components.month}-${components.day}T${components.hour}:${components.minute}:${components.second}`)
return new Intl.DateTimeFormat(locales, { dateStyle }).format(dateToFormat)
}

return ''
}
2 changes: 1 addition & 1 deletion src/routes/[...slug]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
<h1>{data.meta.title}</h1>
{/if}
<span class="post-meta">
<time class="post-date" datetime={formatDate(data.meta.date, 'long')}>{formatDate(data.meta.date)}</time>
<time class="post-date" datetime={formatDate(data.meta.date, 'full')}>{formatDate(data.meta.date)}</time>
<ul class="post-tags">
{#each data.meta.tags as tag}
Expand Down

0 comments on commit 5024c5e

Please sign in to comment.