How can I get the day that the next month starts on? (Monday Tuesday etc.).
I tried the following but it returns more than just the day.
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m 1, 0);
CodePudding user response:
You're almost there, just add this after your last line of code to get the name of the day
var dayName = lastDay.toLocaleDateString('en-us', { weekday: 'long' });
Also keep in mind that Date
constructor's second parameter is monthIndex
MDN.
You should add m
by 1 to get next month's first day and add it by 2 and provide date = 0
to get the last day of the next month.
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m 1, 1);
var lastDay = new Date(y, m 2, 0);
var firstDayName = firstDay .toLocaleDateString('en-us', { weekday: 'long' });
var lastDayName = lastDay.toLocaleDateString('en-us', { weekday: 'long' });
console.log(firstDayName, lastDayName)
CodePudding user response:
Your current code is getting Date
instances for the first and last day of the current month. So first you'll need to fix that. Then, if you want day numbers instead, you have to call getDay
to get the values (0 = Sunday through 6 = Saturday):
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() 1; // 1 = next month
const firstDay = new Date(year, month, 1).getDay();
const lastDay = new Date(year, month 1, 0).getDay();
console.log({firstDay, lastDay});
As I write this on July 31st, that shows 1
and 3
, telling us that August 2022 starts on Monday and ends on Wednesday.
CodePudding user response:
You'll need to use Date.getDay
to get a number in [0, 6]
, which, assuming you want the name of the weekday in question, you can then use to lookup the relevant name. For example:
function getWeekday(date) {
switch (date.getDay()) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
}
}
In your original code you also never correctly managed to get a Date
object for the first day of the next month. This is how you would go about that:
var today = new Date();
var y = today.getFullYear(), m = today.getMonth();
var firstDayOfNextMonth = new Date(y, (m % 12) 1, 1);
console.log(getWeekday(firstDayOfNextMonth));
// "Monday"
CodePudding user response:
I just took the current date and got the first day of the month. Then we just converted this to string. It's working. Try this:
const date = new Date(); // current date 1/8/2022
const nextMonth = new Date(date.getFullYear(), date.getMonth() 1, 1); //first day of next month
const nextMonthStartDay = nextMonth.toLocaleDateString('en-US', { weekday: 'long' }); //convert to date string
console.log(nextMonthStartDay) //Thursday