I want to show "The last days of the offer" for example:
Offer days: 1, 2 and 3 of June 2023.
My code works fine, until I get to the start of a new month.
At the beginning of each month, it shows like this:
0, 1 and 2 of June 2023 but it should be 31, 1 and 2 of June 2023.
That is, I need to show the last day of the previous month instead of 0.
Or the last two days of the month, in this example: 30, 31 and 1 of June 2023.
PS: The date format may look wrong for English speakers, because it is in Portuguese format.
PPS: Usually I have to use it in more than one place on the same page.
PPPS: Sorry for the poor code, I’m learning.
<span id="diaspromocao1"></span>
<span id="diaspromocao2"></span>
var months = new Array(12);
months[0] = "Janeiro";
months[1] = "Fevereiro";
months[2] = "Março";
months[3] = "April";
months[4] = "Maio";
months[5] = "Junho";
months[6] = "Julho";
months[7] = "Augosto";
months[8] = "Setembro";
months[9] = "Outobro";
months[10] = "Novembro";
months[11] = "Dezembro";
var current_date = new Date();
current_date.setDate(current_date.getDate() + 0);
month_value = current_date.getMonth();
day_value = current_date.getDate();
day_value1 = current_date.getDate() - 1;
day_value2 = current_date.getDate() - 2;
year_value = current_date.getFullYear();
document.getElementById("diaspromocao1").innerHTML = + day_value2 + ", " + day_value1 + " e " + day_value + " de "+ months[month_value] + " de " + year_value;
document.getElementById("diaspromocao2").innerHTML = + day_value2 + ", " + day_value1 + " e " + day_value + " de "+ months[month_value] + " de " + year_value;
I don’t know what else to do to resolve this. Would anyone here be able to help me out? Thank you!
2
Answers
If you use the
Date
object to go back to the previous days by doingcurrent_date.setDate(current_date.getDate() - 1)
, it will handle wrapping around. Here’s a simpler example. Note that the month will also change (of course!):Side note:
current_date.setDate(current_date.getDate() + 0);
doesn’t do anything, you can just remove it.getDate just returns the day of month as a number. So if it’s the first day of a month (
1
) you will receive0
after you subtracted one day.This is not how temporal, arithmetic operations work on
Date
. You need to set the new value on the existing instance ofDate
. In case of an overflow (start/end of months for example) the class will take care of it.Also note that
Date
is mutable so you should work with individual instances for your separate dates.