javascripthtmldatedayofmonth

Using computer date and adding a day indicator


I have been trying to display the following "on this 4th day of January in the year 2022"

using javascript on an HTML page

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
const d = new Date();
var dayn = d.getDay()
var dayString;
if (dayn == 1) {
  dayString = "</b><sup>st</sup>"
} else if (dayn == 3) {
  dayString = "</b><sup>rd</sup>"
} else if (dayn >= 4) {
  dayString = "</b><sup>th</sup>"
} else {
  dayString = "</b><sup>nd</sup>"
}
var dateStr = "<b>" + dayn + dayString + "</b> day of<b> " + monthNames[d.getMonth()] + "</b> in the year <b>" + d.getFullYear(); + "</b>"
document.write(dateStr);

but for some reason it is displaying today as the 2nd and not the 4th and

where I want to display ie. 4th March 2022 (today +89 days) it is failing to do so...

So the aim is to on the first line display:

"on this 4th day of January in the year 2022"

and on the next line

"no later than 3rd day of March 2022"


Solution

  • const monthNames = ["January", "February", "March", "April", "May", "June",
      "July", "August", "September", "October", "November", "December"
    ];
    const d = new Date();
    var dayn = d.getDate();
    var dayString;
    if (dayn == 1) {
      dayString = "</b><sup>st</sup>"
    } else if (dayn == 3) {
      dayString = "</b><sup>rd</sup>"
    } else if (dayn >= 4) {
      dayString = "</b><sup>th</sup>"
    } else {
      dayString = "</b><sup>nd</sup>"
    }
    var dateStr = "<b>" + dayn + dayString + "</b> day of<b> " + monthNames[d.getMonth()] + "</b> in the year <b>" + d.getFullYear(); + "</b>"
    document.write(dateStr);