-1

I would like to retrieve the date in format mm.dd.yy for every upcoming friday. Let's say today is Wednesday, the 9th of September. The next upcoming Friday would be September, 11th or 09/11/2020. How do I program this logic using JavaScript?

var today = Utilities.formatDate(new Date(), "GMT+1", "mm.dd.yy")
var next_friday = ?

Any pointers would help!

ee8291
  • 495
  • 4
  • 9
  • 18

2 Answers2

1

You can do this with JS without any libraries.

First, figure out what 'day' the current date represents. new Date().getDay() will return you a value between 0(sun) - 6(sat). Now that you know what day of the week it is, you can simply do a little math to figure out when the next closest friday is.

const now = new Date();
// The next friday is this many days away. Actually this is a current/next
// thursday and we are adding a day so we can simplify the expression.
const offset =  ((11 - date.getDay()) % 7) + 1;

now.setDate(now.getDate() + offset); // add days to friday to our time.

So all together you can wrap that into a function and stick it in a helpers file somewhere. You can even parameterize the day, so you can find arbitrary days.

const today = new Date("09/13/2020");

const nextDay = (date, day) => {
  const result = new Date(date.getTime());
  const offset = (((day + 6) - date.getDay()) % 7) + 1;
  
  result.setDate(date.getDate() + offset);

  return result;
};

const days = {
  sunday: 0,
  monday: 1,
  tuesday: 2,
  wednesday: 3,
  thursday: 4,
  friday: 5,
  saturday: 6
};

const nextFriday = (date) => nextDay(date, days.friday);

console.log(nextFriday(today)); // hopefully 9/18/2020

Formatting would just be finding each component from the result date and concatenating them together.

const today = new Date("09/13/2020");

const formatDate = (date) => {
  const month = `${date.getMonth() + 1}`.padStart(2, "00");
  const day = `${date.getDate()}`.padStart(2, "00");
  const year = date.getFullYear();
  
  return `${month}.${day}.${year}`;
}

console.log(formatDate(today));
Brenden
  • 1,947
  • 1
  • 12
  • 10
0

Using https://github.com/datejs/Datejs

console.log(Date.next().friday())
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>

var today = Utilities.formatDate(new Date.next().friday(), "GMT+1", "mm.dd.yy")
var next_friday = Utilities.formatDate(Date.next().friday(), "GMT+1", "mm.dd.yy")
Ronald M. Kasendwa
  • 410
  • 1
  • 4
  • 11