Skip to content

Instantly share code, notes, and snippets.

@leandroandrade
Last active May 3, 2023 17:22
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 leandroandrade/0e2e10db68867438139217616e1a8e29 to your computer and use it in GitHub Desktop.
Save leandroandrade/0e2e10db68867438139217616e1a8e29 to your computer and use it in GitHub Desktop.
const daysMonth = 30;
const months = 12
const diffDates = (first, second) => {
const difference = first.getTime() - second.getTime();
return Math.ceil(difference / (1000 * 3600 * 24));
}
function calculate(end, date) {
const totalDays = diffDates(end, date);
if (totalDays < 0) return "Expirou"
if (totalDays === 0) return "Hoje"
if (totalDays === 1) return "Amanhã"
if (totalDays <= 30) return `${totalDays} dias`
const totalMonths = Math.floor(totalDays / daysMonth);
if (totalMonths <= 1) return `${totalMonths} mês`
if (totalMonths <= 11) return `${totalMonths} meses`
const years = Math.floor(totalMonths / months)
if (years <= 1) return `${years} ano`
return `${years} anos`
}
console.log('Expirou:', calculate(new Date('2023-05-02'), new Date('2023-05-03')) === 'Expirou');
console.log('Hoje:', calculate(new Date('2023-05-03'), new Date('2023-05-03')) === 'Hoje');
console.log('Amanhã:', calculate(new Date('2023-05-04'), new Date('2023-05-03')) === 'Amanhã');
console.log('2 dias:', calculate(new Date('2023-05-05'), new Date('2023-05-03')) === '2 dias');
console.log('30 dias:', calculate(new Date('2023-06-02'), new Date('2023-05-03')) === '30 dias');
console.log('1 mês:', calculate(new Date('2023-06-03'), new Date('2023-05-03')) === '1 mês');
console.log('11 meses:', calculate(new Date('2024-04-03'), new Date('2023-05-03')) === '11 meses');
console.log('1 ano:', calculate(new Date('2024-05-03'), new Date('2023-05-03')) === '1 ano');
console.log('5 anos:', calculate(new Date('2028-05-03'), new Date('2023-05-03')) === '5 anos');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment