The version I originally started with has first day of week as Monday, but I need it to be Sunday:
<script>
import { beforeUpdate } from 'svelte';
import {
startOfMonth,
addMonths,
format,
subMonths,
addDays,
startOfWeek,
sub,
add,
eachDayOfInterval,
getDay,
isToday
} from 'date-fns';
let firstDayOfWeek;
let currentMonth;
let nextMonth;
let previousMonth;
let daysOfCurrentMonth;
let weekdayOffset;
let weekNames;
beforeUpdate(() => {
firstDayOfWeek = startOfWeek(new Date(), {
locale: navigator?.language.split('-').pop().toLowerCase() || 'us',
weekStartsOn: 0
});
currentMonth = startOfMonth(new Date());
nextMonth = startOfMonth(addMonths(new Date(currentMonth), 1));
previousMonth = startOfMonth(subMonths(new Date(currentMonth), 1));
daysOfCurrentMonth = eachDayOfInterval({
start: currentMonth,
end: sub(nextMonth, { days: 1 })
});
weekdayOffset = (getDay(currentMonth) + 7) % 7 || 7;
weekNames = [...Array(7)].map((_, index) => format(addDays(firstDayOfWeek, index), 'EEEEEE'));
});
</script>
{#if weekNames}
<div class="week-days">
{#each weekNames as weekName}
<p>{weekName}</p>
{/each}
</div>
{/if}
{#if daysOfCurrentMonth}
<div class="days">
{#each daysOfCurrentMonth as day, index}
<p
class="day"
style={`
grid-column: column(${index});
grid-column-start: ${index === 0 ? weekdayOffset : 0};
color: ${isToday(day) ? 'red' : 'white'};
`}
>
{format(day, 'dd')}
</p>
{/each}
</div>
{/if}
<style>
.days,
.week-days {
display: grid;
grid-template-columns: repeat(7, 50px);
grid-column: 7;
}
</style>
I believe the problem resides with this line:
weekdayOffset = (getDay(currentMonth) + 7) % 7 || 7;
It has Feb 1, 2022 starting on Monday when it should be Tuesday.
Here is a fiddle: https://codesandbox.io/s/naughty-surf-bovu8?file=/Button.svelte