Skip to content

Commit 85a927c

Browse files
committed
refactor: [#297] code cleanup
1 parent 8e47ec0 commit 85a927c

File tree

2 files changed

+20
-19
lines changed

2 files changed

+20
-19
lines changed

components/torrent/TorrentCreationDateTab.vue

+4-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
<template v-if="!collapsed">
1515
<div class="flex flex-col w-full h-full p-6 grow bg-base-100 rounded-2xl">
1616
<template v-if="torrent.creation_date">
17-
{{ unixTimeToHumanReadableUTC(torrent.creation_date) }}
17+
{{ formatedDateFromTimestamp }}
1818
</template>
1919
<template v-else>
2020
<span class="italic text-neutral-content">No creation date provided.</span>
@@ -30,7 +30,7 @@ import { TorrentResponse } from "torrust-index-types-lib";
3030
import { PropType } from "vue";
3131
import { ref } from "#imports";
3232
import Markdown from "~/components/Markdown.vue";
33-
import { unixTimeToHumanReadableUTC } from "~/src/helpers/DateConverter";
33+
import { formatTimestamp } from "~/src/helpers/DateConverter";
3434
3535
const collapsed = ref(false);
3636
@@ -41,6 +41,8 @@ const props = defineProps({
4141
}
4242
});
4343
44+
const formatedDateFromTimestamp = formatTimestamp(props.torrent.creation_date);
45+
4446
</script>
4547

4648
<style scoped>

src/helpers/DateConverter.ts

+16-17
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
1-
type UnixTime = number;
1+
type UnixTimestamp = number;
2+
type FormattedDate = string;
23

34
class InvalidDateError extends Error {}
4-
class WrongTimestamp extends Error {}
55

6-
// Takes the date in seconds from Epoch time and converts it to human readable format.
6+
/**
7+
* Takes the date in seconds from Unix Epoch time and converts it to human readable format.
8+
*
9+
* For example: 1701688451 -> "Mon Dec 04 2023"
10+
*/
711

8-
export function unixTimeToHumanReadableUTC (creationDate: UnixTime) {
9-
let milliseconds;
10-
let convertedDate;
11-
try {
12-
milliseconds = creationDate * 1000;
13-
} catch (error) {
14-
return new WrongTimestamp(`Could not convert ${creationDate} to milliseconds`);
15-
}
16-
try {
17-
convertedDate = new Date(milliseconds);
18-
} catch (error) {
19-
return new InvalidDateError(`Could not create a new date from ${milliseconds}`);
20-
}
21-
return !isNaN(convertedDate.valueOf()) ? convertedDate.toDateString() : new InvalidDateError(`Could not create a valid date from ${milliseconds}`);
12+
export function formatTimestamp (creationDate: UnixTimestamp): FormattedDate | Error {
13+
const milliseconds = creationDate * 1000;
14+
15+
const convertedDate = new Date(milliseconds);
16+
17+
return isNaN(convertedDate.valueOf())
18+
? new InvalidDateError(
19+
`Invalid date. Could not create a new date from timestamp value: ${creationDate}`)
20+
: convertedDate.toDateString();
2221
}

0 commit comments

Comments
 (0)