Hackerss.com

hackerss
hackerss

Posted on

A calendar which tell me when will be full moon in Javascript

A calendar which tell me when will be full moon - Javascript:


//function to calculate the next full moon
function nextFullMoon(date) {
  //create a new date object
  const nextFullMoon = new Date(date);

  //get the current month
  const currentMonth = nextFullMoon.getMonth();

  //get the current year
  const currentYear = nextFullMoon.getFullYear();

  //get the current day
  const currentDay = nextFullMoon.getDate();

  //set the date to the first day of the month
  nextFullMoon.setDate(1);

  //set the month to the next month
  nextFullMoon.setMonth(currentMonth + 1);

  //if the month is greater than 11, set it to 0 and increment the year by 1
  if (nextFullMoon.getMonth() > 11) {
    nextFullMoon.setMonth(0);
    nextFullMoon.setFullYear(currentYear + 1);
  }

  //set the date to the first day of the month
  nextFullMoon.setDate(1);

  //subtract one day from the date to get the last day of the previous month
  nextFullMoon.setDate(nextFullMoon.getDate() - 1);

  //if the day of the week is Sunday, subtract 3 days, otherwise subtract 2
  if (nextFullMoon.getDay() === 0) {
    nextFullMoon.setDate(nextFullMoon.getDate() - 3);
  } else {
    nextFullMoon.setDate(nextFullMoon.getDate() - 2);
  }

  //if the day is not equal to the current day, return the date, otherwise return null
  if (nextFullMoon.getDate() !== currentDay) {
    return nextFullMoon;
  } else {
    return null;
  }
}

//example
const result = nextFullMoon(new Date());

//output
console.log(result); //Tue Dec 29 2020 00:00:00 GMT+0100 (Central European Standard Time)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)