0

I need to generate the current date in the following format:

Month-Day-Year [Day of Week]

For example:

August-15-2021 [Sunday]

I need the webpage to update the date in this format every time I open the web page, so tomorrow it would say the 16. I have a function that creates an array for each month and day of the week to convert the numbers to text. I have not been able to get very far; I am first trying to get the month figured out and I feel like the rest will come together. I have one script section that has the following:

<script language="JavaScript">

function monthText(month)
{
  var MonthName = new
  Array ('January','February','March','April','May','June',
         'July','August','September','October','November','December');
  return( MonthName[month] );
}

function weekText(week)
{
  var WeekName = new
  Array ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  return( WeekName[week] );
}

</script>

Then I have the following to try and produce the date:

<script language="JavaScript">

  var today = new Date();
  var dateStr = monthText;

  document.write(dateStr);


    var dateStr = monthText;

    document.write(dateStr);
</script>

I am an absolute novice at HTMl and Javascript; I feel like I am over complicating this or missing something.

Spectric
  • 30,714
  • 6
  • 20
  • 43
RMaxwell87
  • 119
  • 8
  • Does this answer your question? [How to format a JavaScript date?](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Heretic Monkey Aug 15 '21 at 20:14

1 Answers1

0

Consider using Date.toLocaleString() instead, which does the conversion for you:

const date = new Date();
const dayMonthYear = date.toLocaleString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }).replaceAll(", ", "-").replaceAll(" ", "-");
const weekday = date.toLocaleString('en-US', { weekday: 'long' })
document.write(dayMonthYear + ' [' + weekday + ']');
Spectric
  • 30,714
  • 6
  • 20
  • 43