forked from torrust/torrust-index-gui
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: [torrust#297] new error checks and refactoring
Date converter helper function now throws errors if the timestamp passed as argument is not an integer and if the Date() constructor returns an invalid date.
- Loading branch information
Showing
2 changed files
with
26 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,34 @@ | ||
type UnixTime = number; | ||
|
||
function isValidDate (date: Date) { | ||
return date instanceof Date && !isNaN(date.valueOf()); | ||
} | ||
class InvalidDateError extends Error {} | ||
|
||
// Takes the date in seconds from Epoch time and converts it to human readable format. | ||
|
||
export function unixTimeToHumanReadableUTC (seconds: UnixTime) { | ||
export function unixTimeToHumanReadableUTC (creationDate: UnixTime) { | ||
try { | ||
return dateFromSeconds(creationDate); | ||
} catch (error) { | ||
return ("Invalid date"); | ||
} | ||
} | ||
|
||
function dateFromSeconds (seconds: number) { | ||
if (!validateTimestamp(seconds)) | ||
{ throw new TypeError("Torrent creation date is not an integer"); } | ||
|
||
const milliseconds = seconds * 1000; | ||
const convertedDate = new Date(milliseconds); | ||
|
||
return isValidDate(convertedDate) ? convertedDate.toDateString() : "Invalid date"; | ||
if (!validateDate(convertedDate)) | ||
{ throw new InvalidDateError("Date is not valid"); } | ||
|
||
return convertedDate.toDateString(); | ||
} | ||
|
||
function validateDate (date: Date) { | ||
return date instanceof Date && !isNaN(date.valueOf()); | ||
} | ||
|
||
function validateTimestamp (timestamp: UnixTime) { | ||
return Number.isInteger(timestamp); | ||
} |