0

I'm working on making a webpage that displays the next date for the Food Pantry. It happens on the second Friday of the month. I grabbed this current code from this question and I think I was able to modifiy it to fit my needs. However, I would like it to display in a 'April, 10th' format instead of '04/10/2020'. I have an extremely basic grasp of Javascript so if you explain it like I'm five would be helpful.

Also, if the second Friday is the current day, it would be great if it could say Today.

Thank you!

Date.prototype.nextsecondFriday = function (){
            // Load the month.
            var target = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 0);
            var today = new Date();

            // Check to see if the 1st is on a Friday.
            var isFriday = (target.getDay() == 1);

            // Jump ahead two weeks from the 1st, and move back the appropriate number of days to reach the preceding Friday.
            // i.e. If the 1st is a Thursday, we would move back three days.
            var targetDate = 12 - (target.getDay() - 1);

            // Quick adjustment if the 1st is a Friday.
            if (isFriday) targetDate -= 4;

            // Move to the second Friday in the month.   
            target.setDate(targetDate);

            // Second Friday is before today's date, so find the second Friday next month.
            if (today > target) {
                //return "<em>" + target.toLocaleDateString() + " is in the past...</em>";
                target.setMonth(target.getMonth() + 1);
                return target.nextsecondFriday();
            }

            // Format and return string date of second Friday.
            return target.toLocaleDateString();
        }
        
        var secondFridayDateString = new Date().nextsecondFriday();

        document.getElementById("dynamicdate").innerHTML = secondFridayDateString;
<p>Our next food pantry is <span id="dynamicdate">Second Friday</span>.</p>
Connor
  • 7
  • 5

5 Answers5

0

Try new Intl.DateTimeFormat('en-US', options).format(target)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

Date.prototype.nextsecondFriday = function (){
            // Load the month.
            var target = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 0);
            var today = new Date();

            // Check to see if the 1st is on a Friday.
            var isFriday = (target.getDay() == 1);

            // Jump ahead two weeks from the 1st, and move back the appropriate number of days to reach the preceding Friday.
            // i.e. If the 1st is a Thursday, we would move back three days.
            var targetDate = 12 - (target.getDay() - 1);

            // Quick adjustment if the 1st is a Friday.
            if (isFriday) targetDate -= 4;

            // Move to the second Friday in the month.   
            target.setDate(targetDate);

            // Second Friday is before today's date, so find the second Friday next month.
            if (today > target) {
                //return "<em>" + target.toLocaleDateString() + " is in the past...</em>";
                target.setMonth(target.getMonth() + 1);
                
                return target.nextsecondFriday();
            }
            let options = { year: 'numeric', month: 'long', day: 'numeric' };

            // Format and return string date of second Friday.
            return new Intl.DateTimeFormat('en-US', options).format(target);
        }
        
        var secondFridayDateString = new Date().nextsecondFriday();

        document.getElementById("dynamicdate").innerHTML = secondFridayDateString;
<p>Our next food pantry is <span id="dynamicdate">Second Friday</span>.</p>
Gaurav Singh
  • 369
  • 1
  • 6
  • Thanks for taking the time to write this out. The comments are really helpful. I was looking to have it formatted without the 2020 and have a 'th' or other suffix on the day. But otherwise a great solution as well. – Connor Apr 03 '20 at 00:16
0

I would modify the nextsecondFriday function to return the date object instead of a formatted string (just drop the toLocaleDateString() call).

Then write another function formatDate which receives a date and returns a formatted string.

Then call nextsecondFriday to get the date and format it usingformatDate.

The code for formatting (the formatDate function), if you require that specific format (the colon and the 'th' etc), would probably be something like:

const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
const monthOptions = { month: 'long' };
const dayOptions = { day: 'numeric' };
const formattedDate = event.toLocaleDateString('en-US', monthOptions) + ', ' + event.toLocaleDateString('en-US', dayOptions));
// then check event.getDay() and append 'st', 'nd', 'rd' or 'th' to formattedDate as needed

But if you can go with another format then just a single call to toLocaleDateString could be enough - check toLocaleDateString documentation on MDN for details.

Jakub Januszkiewicz
  • 4,380
  • 2
  • 37
  • 54
0

See toDateString you just have to change this statement

 return target.toDateString();
0
options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
secondFridayDateString.toLocaleDateString("en-us", options)

you need to set the format, check that.

you can play with this in the console just doing:

let date = new Date()
options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
date.toLocaleDateString("en-us", options) //set your locale as you want i.e. es-ar or any locale
Luchux
  • 803
  • 1
  • 7
  • 17
0

The below code find the second friday for any Date()

Date.prototype.nextsecondFriday = function() {
  // get second firday for given month and year
  const secondFriday = (year, month) => {
    // first day of the month
    let date = new Date(year, month, 1);
    let dayDifference = 5 - date.getDay();

    // get second friday of the month
    if (dayDifference < 0) {
      date.setDate(date.getDate() + (14 + (-1 * dayDifference)));
    } else if (dayDifference >= 0) {
      date.setDate(date.getDate() + 7 + dayDifference);
    }

    return date;
  };

  // format date to "April 10th"
  const formatDate = (date) => {
    const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const month = months[date.getMonth()];
    const day = date.getDate();
    let suffix = 'th';
    const j = day % 10,
      k = day % 100;

    if (j == 1 && k != 11) {
      suffix = "st";
    } else if (j == 2 && k != 12) {
      suffix = "nd";
    } else if (j == 3 && k != 13) {
      suffix = "rd";
    }
    return `${month} ${day}${suffix}`;
  };


  let date = this;
  let closestSecondSaturday;
  do {
    let secondFridayOfThisMonth = secondFriday(date.getFullYear(), date.getMonth());
    if (secondFridayOfThisMonth.getDate() === date.getDate()) {
      closestSecondSaturday = "Today";
    } else if (secondFridayOfThisMonth.getDate() >= date.getDate()) {
      closestSecondSaturday = formatDate(secondFridayOfThisMonth);
    } else {
      // if current date has crossed the second friday, move to the next month
      date.setMonth(date.getMonth() + 1);
    }
  } while (!closestSecondSaturday)
  return closestSecondSaturday;
};

// sample call
document.write(new Date().nextsecondFriday());
j3ff
  • 5,719
  • 8
  • 38
  • 51
Cs Vignesh
  • 26
  • 4