Skip to content

Commit

Permalink
fix: validate date
Browse files Browse the repository at this point in the history
  • Loading branch information
nunof07 committed Apr 29, 2021
1 parent 342a604 commit 168cca8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/isValidDate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"use strict";

module.exports = function isValidDate(maybeDate) {
if (!maybeDate) {
return false;
}

if (!(maybeDate instanceof Date)) {
return false;
}

if (Number.isNaN(maybeDate.getTime())) {
return false;
}

return true;
};
17 changes: 17 additions & 0 deletions src/isValidDate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"use strict";

const test = require("ava");

const isValidDate = require("./isValidDate");

test("is valid date", (t) => {
t.true(isValidDate(new Date()));
});

test("is not empty date", (t) => {
t.false(isValidDate());
});

test("is not invalid date object", (t) => {
t.false(isValidDate(new Date("hello")));
});
6 changes: 6 additions & 0 deletions src/sitemapDateTime.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
"use strict";

const isValidDate = require("./isValidDate");

module.exports = function sitemapDateTime(date) {
if (!date) {
return;
}

const dateObject = typeof date === "string" ? new Date(date) : date;

if (!isValidDate(dateObject)) {
return;
}

return dateObject.toISOString();
};

0 comments on commit 168cca8

Please sign in to comment.