0

This is the code I have right now.

var DateHelper = {
    addDays : function(aDate, numberOfDays) {
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
        return aDate;                                  // Return the date
    },
    format : function format(date) {
        return [

           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
       ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
           date.getFullYear()                          // Get full year
        ].join('/');                                   // Glue the pieces together
    }
}

// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Add 10 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.write( DateHelper.format(DateHelper.addDays(new Date(), 7)));
<!DOCTYPE html>
<html>
  <body>
    <h2>My First Web Page</h2>
     <p>My first paragraph.</p>
     <p>future date code.</p>
     <script>
         document.write("Offer Ends:");
     </script>
</html>
This code works perfectly. It displays Offer Ends: 11/13/2019 (a week from now) BUT I need a different format so it says: "Offer Ends: November 13, 2019"

How would I add this formatting into the original working code?

Hitesh Tripathi
  • 856
  • 1
  • 11
  • 23
  • 2
    take a look into https://momentjs.com/ is a awesome library to parse/process dates. – David Nov 06 '19 at 16:36
  • Are you talking of a week from **now** or a week from a **specific date**? – Udo E. Nov 06 '19 at 16:38
  • 1
    You could change the `DateHelper.format` function to use `toLocaleDateString()` - explanation [here](https://stackoverflow.com/a/34015511/3063706) – Danny Nov 06 '19 at 16:39

1 Answers1

0

You need a function to turn the month number into the month name. This can be achived with a simple list. Then join the values with a space instead of a slash.

format : function format(date) 
{
           let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'Septemper', 'November', 'December'];
           return [months[date.getMonth()],
                   date.getDate().toString().padStart(2, '0')+',',
                   date.getFullYear()].join(' ');
}

The downside to this is that the month names are not localisable.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
  • I am not very familiar with JavaScript. The solution I am currently using is something I found on this site from a while back. How would I incorporate your code into my existing code to make it function properly? – JakeKnowsNothing Nov 06 '19 at 17:40
  • You have a function called format in your code. Replace that with this – Matt Ellen Nov 06 '19 at 18:41