Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torressam333/0a3cd94f4f6b14b3dd9efdc7694e708b to your computer and use it in GitHub Desktop.
Save torressam333/0a3cd94f4f6b14b3dd9efdc7694e708b to your computer and use it in GitHub Desktop.
Parse a credit card date string into a date object and determine if it is expired - JavaScript
/**
Takes in the expirationDate param as: "3/2025" or "03/2025" etc...
Rookie Implementation
**/
export default function isCreditCardExpired(expirtationDate) {
const now = new Date();
const currentMonth = now.getMonth() + 1; // 9
const currentYear = now.getFullYear(); // 2022
// Split + convert vals to INT
const splitExpDate = expirtationDate.split("/").map((el) => +el);
let ccMonth = splitExpDate[0];
let ccYear = splitExpDate[1];
let isExpired;
if (currentYear > ccYear) {
console.log("expired year, dude");
isExpired = true;
} else if (currentYear === ccYear && currentMonth > ccMonth) {
// Year is the same so lets check months
console.log("Good year but expired month, dude");
isExpired = true;
} else if (currentYear === ccYear && currentMonth === ccMonth) {
console.log("Not expired");
isExpired = false;
} else {
console.log("Still NOT expired");
isExpired = false;
}
return isExpired;
}
const test = "6/2025";
const test2 = "12/2018";
const test3 = "10/2022";
console.log(isCreditCardExpired(test)); // False - not expired
console.log(isCreditCardExpired(test2)); // True - expired
console.log(isCreditCardExpired(test3)); // False - expired
/**
Better implentation.
**/
function isCreditCardExpired(expirtationDate) {
// Split + convert vals to INT
const splitExpDate = expirtationDate.split("/").map((el) => +el);
const [ccMonth, ccYear] = splitExpDate;
const today = new Date();
const expirationDay = new Date();
expirationDay.setFullYear(ccYear, ccMonth - 1, expirationDay.getDate());
return expirationDay < today;
}
const test = "6/2025";
const test2 = "12/2018";
const test3 = "10/2022";
console.log(isCreditCardExpired(test)); // False - not expired
console.log(isCreditCardExpired(test2)); // True - expired
console.log(isCreditCardExpired(test3)); // False - expired
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment