Skip to content

Instantly share code, notes, and snippets.

@andirady
Created June 11, 2019 07:04
Show Gist options
  • Save andirady/256ded733a80749e3d9f43b2cd5e9875 to your computer and use it in GitHub Desktop.
Save andirady/256ded733a80749e3d9f43b2cd5e9875 to your computer and use it in GitHub Desktop.
Calendar component using sveltejs
<script>
const ONE_DAY = 24*60*60*1000;
const DAYS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
export
let date, month, year;
function getCalendar(year, month) {
var first = new Date(year, month);
var cells = [];
var rows = [cells];
var d = new Date(first.getTime() - ONE_DAY * first.getDay());
var i = 0;
for (
let d = new Date(first.getTime() - ONE_DAY * first.getDay());
(d.getMonth() <= month && d.getYear() <= year) || i % 7 !== 0 || rows.length < 7;
d = new Date(d.getTime() + ONE_DAY)
) {
cells.push(d);
if ((++i % 7) === 0) {
cells = [];
rows.push(cells);
}
}
return rows;
}
</script>
<style>
table {
border-collapse: collapse;
}
td {
text-align: center;
width: 2rem;
height: 2rem;
margin: .5rem;
}
</style>
<table>
<thead>
<tr>
{#each DAYS as day}
<th>{day}</th>
{/each}
</tr>
</thead>
<tbody>
{#each getCalendar(year,month) as rows}
<tr>
{#each rows as cell}
<td>
{#if cell.getMonth() === month}
<a href="javascript:;">
{#if cell.getDate() === date}
<b>{cell.getDate()}</b>
{:else}
{cell.getDate()}
{/if}
</a>
{:else}
{cell.getDate()}
{/if}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment