Calculate the dates correctly

Hi everyone,

I have 2 questions:

  1. I want to show the date of the next payment which is between 1st and 5th of the next month. For example, today is 15 December and the interface should display “Jan 1st - 5th”

  2. I want to show the date of when yearly subscription ends. For example, the beginning of the subscription is 14.08.2023, the end of the subscription is “13.08.2024”. It should also consider the leap years

But i don’t quite understand the formulas in Glide. I know it’s a complicated question, but could anyone please help me? Thanks

1 Like

Hi @Alexandra_111,

Not sure if there’s a easy way to achieve this but here’s my attempt with JS!

For the 1st question ( actually not sure if I understand you correctly :slightly_smiling_face: )

image

function getNextPaymentDate(p1) {
  if (!p1) {
    return '';
  }

  const today = new Date(p1);
  const nextMonth = new Date(today.setMonth(today.getMonth() + 1));

  const nextPaymentDate = nextMonth.getDate() >= 1 && nextMonth.getDate() <= 5
    ? nextMonth
    : new Date(nextMonth.getFullYear(), nextMonth.getMonth(), 1);

  return `${nextPaymentDate.toLocaleString('en-us', { month: 'short' })} 1st - 5th`;
}

const result = getNextPaymentDate(p1);
return(result);

For the 2nd question

image

function getSubscriptionEndDate(p1) {
  if (!p1) {
    return '';
  }

  const startDate = new Date(p1);
  const endYear = startDate.getFullYear() + 1;
  const endDate = new Date(endYear, startDate.getMonth(), startDate.getDate());

  if ((endYear % 4 === 0 && endYear % 100 !== 0) || (endYear % 400 === 0)) {
    endDate.setDate(endDate.getDate() - 1); 
  }

  return endDate.toLocaleDateString('en-US');
}

const result = getSubscriptionEndDate(p1);
return(result);

Thank you

3 Likes

Hi @Dilon_Perera

Looks like everything works correctly! :star_struck:

Thanks a lot, you made my day

1 Like

Please test if this works correctly in iOS/MacOS. I have been bitten by using Date functions in JS with iOS/MacOS before.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.