Skip to content

Commit

Permalink
Attempt at making dates have correct timezone
Browse files Browse the repository at this point in the history
  • Loading branch information
Deflaktor committed Jul 15, 2024
1 parent 1139280 commit 02d0e7a
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 87 deletions.
81 changes: 81 additions & 0 deletions public/dateutils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const UNIT_DAY = 24 * 60 * 60 * 1000;
const UNIT_WEEK = 7 * UNIT_DAY;
const UNIT_MONTH = 30 * UNIT_DAY;

/**
* Calculates the difference between the target date and today in the specified unit.
*
* @param {Date} targetDate - The date to compare with today.
* @param {number} unit - The unit to use for the difference calculation (e.g., milliseconds per day).
* @returns {number} The difference in the specified unit.
*/
function ago(targetDate, unit) {
const today = new Date();
today.setHours(0, 0, 0, 0);
targetDate.setHours(0, 0, 0, 0);
const differenceMs = today.getTime() - targetDate.getTime();
const differenceDays = Math.floor(differenceMs / unit);
return differenceDays;
}

/**
* Calculates the number of days between the target date and today.
*
* @param {Date} targetDate - The date to compare with today.
* @returns {number} The number of days between the target date and today.
*/
function daysAgo(targetDate) {
return ago(targetDate, UNIT_DAY);
}

/**
* Calculates the number of weeks between the target date and today.
*
* @param {Date} targetDate - The date to compare with today.
* @returns {number} The number of weeks between the target date and today.
*/
function weeksAgo(targetDate) {
return ago(targetDate, UNIT_WEEK);
}

/**
* Calculates the number of months between the target date and today.
*
* @param {Date} targetDate - The date to compare with today.
* @returns {number} The number of months between the target date and today.
*/
function monthsAgo(targetDate) {
return ago(targetDate, UNIT_MONTH);
}

/**
* Converts the target date into a human-readable string representing the time difference from today.
*
* @param {Date} targetDate - The date to convert.
* @returns {string} A human-readable string representing the time difference from today.
*/
function humanReadableDate(targetDate) {
if (daysAgo(targetDate)<1) {
return `today`;
} if (daysAgo(targetDate)<2) {
return `yesterday`;
} else if (daysAgo(targetDate)<30) {
return `${daysAgo(targetDate)} days ago`;
} else if (weeksAgo(targetDate)<10) {
return `${weeksAgo(targetDate)} weeks ago`;
} else if (monthsAgo(targetDate)<10) {
return `${monthsAgo(targetDate)} months ago`;
} else {
return targetDate.toISOString().split('T')[0];
}
}

/**
* Converts a Date object to an ISO 8601 formatted date string (YYYY-MM-DD).
*
* @param {Date} date - The date to be converted.
* @returns {string} The ISO 8601 formatted date string.
*/
function isoDate(date) {
return date.toISOString().split('T')[0];
}
14 changes: 10 additions & 4 deletions src/components/board/boardImage.astro
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
import type { MapDescriptorExtended } from '~/lib/getboards';
import { daysAgo, humanReadableDate, isoDate } from '~/lib/utils';
interface Props {
board: MapDescriptorExtended;
link: boolean;
Expand Down Expand Up @@ -162,20 +161,27 @@ const { board, link, imageHeight } = Astro.props;
</span>
)}
<img class="card-img-top mapCard-image-background" style={`height: ${imageHeight}`} src={`/images/backgrounds/${board.background}.webp`} loading="lazy" />
{ daysAgo(new Date(board.uploadDate)) < 30 && (
{ Date.now() - board.uploadDate < 30 * 24 * 60 * 60 * 1000 && (
<div class="top-right-absolute">
<div class="badge bg-danger" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title={`Uploaded: ${(isoDate(new Date(board.uploadDate)))}`}>New</div>
<div class="badge bg-danger" data-bs-toggle="tooltip" data-bs-placement="top" data-date={board.uploadDate} data-titletemplate={"Uploaded: [date]"}>New</div>
</div>
)}
<div class="bottom-left-absolute">
<div class="badge bg-secondary" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title={(isoDate(new Date(board.lastUpdated)))}>Updated: {humanReadableDate(new Date(board.lastUpdated))}</div>
<div class="badge bg-secondary" data-bs-toggle="tooltip" data-bs-placement="top" data-date={board.lastUpdated} data-titletemplate={"[date]"}>
Updated: <script define:vars={{ lastUpdated: board.lastUpdated }}>document.write(humanReadableDate(new Date(+lastUpdated)));</script>
</div>
</div>
<div class="bottom-right-absolute">
{board.authors?.map((author) => (
<div class="badge bg-primary">{author.url ? (<a class="text-reset" href={ author.url }>{ author.name }</a>) : author.name}</div>
))}
</div>
<script>
document.querySelectorAll('[data-titletemplate]').forEach((element) => {
const el = element as HTMLElement;
el.dataset.bsTitle = el.dataset.titletemplate?.replace("[date]", isoDate(new Date(+el.dataset.date!)));
})

import { Tooltip } from "bootstrap";
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
const _tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new Tooltip(tooltipTriggerEl))
Expand Down
14 changes: 10 additions & 4 deletions src/components/board/boardProperties.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
import type { MapDescriptorExtended } from '~/lib/getboards';
import { isoDate } from '~/lib/utils';
import { isoDate } from '~/lib/dateutils';
interface Props {
board: MapDescriptorExtended;
}
Expand Down Expand Up @@ -52,13 +52,19 @@ const { board } = Astro.props;
<li class="list-group-item d-flex justify-content-between align-items-start">
<div class="ms-2 me-auto">
<div class="fw-bold small">Last Updated</div>
{isoDate(new Date(board.lastUpdated))}
<script is:inline define:vars={{ lastUpdated: board.lastUpdated }}>document.write(humanReadableDate(new Date(+lastUpdated)));</script>
<span class="text-secondary small px-2">
<script is:inline define:vars={{ lastUpdated: board.lastUpdated }}>document.write(isoDate(new Date(+lastUpdated)));</script>
</span>
</div>
</li>
<li class="list-group-item d-flex justify-content-between align-items-start">
<div class="ms-2 me-auto">
<div class="fw-bold small">Uploaded</div>
{isoDate(new Date(board.uploadDate))}
<script is:inline define:vars={{ uploadDate: board.uploadDate }}>document.write(humanReadableDate(new Date(+uploadDate)));</script>
<span class="text-secondary small px-2">
<script is:inline define:vars={{ uploadDate: board.uploadDate }}>document.write(isoDate(new Date(+uploadDate)));</script>
</span>
</div>
</li>
</ul>
</ul>
1 change: 1 addition & 0 deletions src/layouts/layout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import Navbar from '~/components/navbar.astro';
<meta name="theme-color" content="black" />
<meta name="color-scheme" content="light dark" />
<meta name="generator" content={Astro.generator} />
<script is:inline src="/dateutils.js"/>
<link rel="icon" href="/favicon.ico" />
<title>Fortune Street Modding - {title}</title>
</head>
Expand Down
18 changes: 17 additions & 1 deletion src/lib/getboards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import DOMPurify from 'isomorphic-dompurify';
import ventureCards from "~/data/venturecards.yml";
import backgrounds, { type Background } from "~/data/backgrounds.yml";
import { execSync } from 'child_process';
import { getRandomDate } from './utils';

export type MapDescriptorExtended = Omit<MapDescriptor1, 'music' | 'changelog' | 'frbFile1' | 'frbFile2' | 'frbFile3' | 'frbFile4' | 'frbFiles' | 'ventureCards'> & {
nameEn: string;
Expand Down Expand Up @@ -174,3 +173,20 @@ function getBoards(): MapDescriptorExtended[] {
}
return boards;
};

function getRandomDate() {
// Get today's date
const today = new Date();

// Calculate 1 year ago from today
const oneYearAgo = new Date();
oneYearAgo.setFullYear(today.getFullYear() - 1);

// Get a random number of milliseconds between oneYearAgo and today
const randomMilliseconds = Math.floor(Math.random() * (today.getTime() - oneYearAgo.getTime())) + oneYearAgo.getTime();

// Create a new Date object using the random milliseconds
const randomDate = new Date(randomMilliseconds);

return randomDate;
}
78 changes: 0 additions & 78 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export function getPathnameWithoutExtension(url: URL) {
return path.join(parsedPath.dir, parsedPath.name);
}


export async function run(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
Expand All @@ -20,80 +19,3 @@ export async function run(command: string): Promise<string> {
});
});
}


export function getRandomDate() {
// Get today's date
const today = new Date();

// Calculate 1 year ago from today
const oneYearAgo = new Date();
oneYearAgo.setFullYear(today.getFullYear() - 1);

// Get a random number of milliseconds between oneYearAgo and today
const randomMilliseconds = Math.floor(Math.random() * (today.getTime() - oneYearAgo.getTime())) + oneYearAgo.getTime();

// Create a new Date object using the random milliseconds
const randomDate = new Date(randomMilliseconds);

return randomDate;
}

export function daysAgo(targetDate: Date): number {
// Get today's date
const today = new Date();

// Calculate the difference in milliseconds
const differenceMs = today.getTime() - targetDate.getTime();

// Convert milliseconds to days
const differenceDays = Math.floor(differenceMs / (1000 * 60 * 60 * 24));

return differenceDays;
}

export function weeksAgo(targetDate: Date): number {
// Get today's date
const today = new Date();

// Calculate the difference in milliseconds
const differenceMs = today.getTime() - targetDate.getTime();

// Convert milliseconds to weeks
const differenceDays = Math.floor(differenceMs / (1000 * 60 * 60 * 24 * 7));

return differenceDays;
}

export function monthsAgo(targetDate: Date): number {
// Get today's date
const today = new Date();

// Calculate the difference in milliseconds
const differenceMs = today.getTime() - targetDate.getTime();

// Convert milliseconds to months
const differenceDays = Math.floor(differenceMs / (1000 * 60 * 60 * 24 * 30));

return differenceDays;
}

export function humanReadableDate(targetDate: Date): string {
if (daysAgo(targetDate)<1) {
return `today`;
} if (daysAgo(targetDate)<2) {
return `yesterday`;
} else if (daysAgo(targetDate)<30) {
return `${daysAgo(targetDate)} days ago`;
} else if (weeksAgo(targetDate)<10) {
return `${weeksAgo(targetDate)} weeks ago`;
} else if (monthsAgo(targetDate)<10) {
return `${monthsAgo(targetDate)} months ago`;
} else {
return targetDate.toISOString().split('T')[0];
}
}

export function isoDate(date: Date): string {
return date.toISOString().split('T')[0];
}

0 comments on commit 02d0e7a

Please sign in to comment.