Skip to content

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

Answer

You have to use d.getDate() instead of d.getDay()

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
const d = new Date();
var dayn = d.getDate();
var endDate = d.setDate(dayn + 89);
var daym = new Date(endDate).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 endDayString;
if (daym == 1) {
  endDayString = "</b><sup>st</sup>"
} else if (daym == 3) {
  endDayString = "</b><sup>rd</sup>"
} else if (daym >= 4) {
  endDayString = "</b><sup>th</sup>"
} else {
  endDayString = "</b><sup>nd</sup>"
}
 
var endDateStr = "<b>" + daym + endDayString + "</b> day of<b> " + monthNames[d.getMonth()] + "</b> in the year <b>" + d.getFullYear(); + "</b>"
document.write(endDateStr);