在Ruby中获取从今日起未来7天的星期名称数组
Generate an Array of the Next 7 Days Starting from Today
Here's a straightforward, reliable way to create this array using JavaScript. It handles the week wrap-around automatically, so you don't have to worry about edge cases like starting on Saturday.
Step-by-Step Solution:
- First, define the full list of week days in the order your example uses (starting with Sunday):
const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
- Get today's position in this array. The
Date.getDay()method returns0for Sunday,1for Monday, up to6for Saturday—this matches our array's index perfectly:
const todayIndex = new Date().getDay();
- Combine two slices of the
daysOfWeekarray to get the next 7 days:- The first slice takes days from today to the end of the week
- The second slice takes days from the start of the week up to (but not including) today
const next7Days = [ ...daysOfWeek.slice(todayIndex), ...daysOfWeek.slice(0, todayIndex) ];
Example Outputs:
- If today is Sunday (
todayIndex = 0):next7Daysbecomes["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] - If today is Saturday (
todayIndex = 6):next7Daysbecomes["Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"]
Quick Notes:
- If you need the week to start with Monday instead, reorder the
daysOfWeekarray and adjust the index calculation (e.g.,(todayIndex + 6) % 7to map Monday to index 0). - For localized day names, replace the strings in
daysOfWeekwith translated versions, or usenew Date().toLocaleDateString('your-language-code', { weekday: 'long' })to fetch dynamic localized names.
内容的提问来源于stack exchange,提问作者Puja Garg
相关产品推荐
相关产品推荐

