Get the week day.
Asked by Sai Siva Kumar about 2 years ago
I want to find the week day from any date and year by using js. Here is my code.
caluClate.addEventListener("click",function(){ let findDay=new Date(date.value.concat(month.value+year.value)) let getDate=findDay.getDay() if(getDate===0){ result.innerHtml="Sunday" }else if(getDate===1){ result.innerHtml="Monday" }else if(getDate===2){ result.innerHtml="Tue" }else if(getDate===3){ result.innerHtml="Wed" }else if(getDate===4){ result.innerHtml="Thu" }else if(getDate===5){ result.innerHtml="Fri" }else if(getDate===6){ result.innerHtml="Sat" } }) Rather creating if else statement is there any alternative approach?
2 Answers
First, it helps if you format your code in code block.
You can use Intl.DateTimeFormat to get Day (Monday, Tuesday...) of any Date object.
var year = 2020, month = 1, day = 26;
var date = new Date(year, month, day);
var dayOfWeek = Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(date)
// dayOfWeek - 'Wednesday'
Reference: MDN Web Docs (Date.prototype.getDay)
I would suggest doing this to get the day of the week
let today = new Date() // to get the full date let todayDay = today.getDate() // to get index of days of the week so getting todayDay will not take you there yet because that will give you the index of the day of the week forexample if todayDay is 1 that means the day is Sunday. There for you can make an array of days ie let daysOfTheWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
Now to get the specific day like today it's Tuesday so your todayDay will be 3 and thus to access that you can use array index forexample,
let myDay = daysOfTheWeek[todayDay]
console.log(myDay) // Tuesday.
Hope that can help you.