![](/img/trans.png)
[英]displaying the day of the week 3 days before today's date using javascript
[英]How to find sunday 9 weeks ago irrespective of what day of the week today is using JavaScript
希望可以有人帮帮我。 我正在尝试编写一个 function 来查找 9 周前的星期日,而不管今天是星期几使用 javascript。
我尝试使用 moment().day(-56) 但它不起作用。 我们还有其他方法可以做到这一点吗?
如果您选择仅使用本机 JS,这可能适合您的需要。
<script>
var today = new Date();
// today.getDay() is current day-of-week (0=Sun ... 6=Sat)
var lastSun9wksAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate()-(9*7+today.getDay()));
// alter display for 9 weeks ago with day-of-week offset
alert(lastSun9wksAgo.toDateString());
</script>
如果重复使用,可以放入两行 function,如下所示:
<script>
function sundayPriorWeeks(weeks) {
var today = new Date();
// today.getDay() is current day-of-week (0=Sun ... 6=Sat)
var lastSun9wksAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate()-(9*7+today.getDay()));
// alter display for # weeks ago with day-of-week offset
return lastSun9wksAgo;
}
alert(sundayPriorWeeks(9).toDateString());
</script>
这是你要找的吗?
console.log(moment().startOf('week').subtract(9,'weeks').format("MM-DD-yyyy"))
周日是一周的开始,所以我们 go 在那里找到了一个基线。 然后,使用 Momentjs 从那里减去 9 周减去 function。格式化为友好的 output。
根据https://momentjscom.readthedocs.io/en/latest/moment/02-get-set/06-day/ ,您可以在 9 个星期天前使用:
moment().day(-63)
我认为您需要分别计算周和工作日。 尝试这样的事情: https://codepen.io/kevinashworth/pen/bGeGjGx
var thisWeek = moment().week()
var theSunday = moment().week(thisWeek - 9).weekday(0).format("dddd, MMMM Do, YYYY")
我假设您需要找到 9 周前的第一个星期日,所以下面的函数可能会有所帮助。
const findNineWeeksAgo = () => { let nineWeeksAgo = new Date('August 19, 1975 23:15:30') const nineWeeksInDays = 63 // You can modify a date using setDate. It automatically corrects for shifting to new months/years etc. nineWeeksAgo.setDate(nineWeeksAgo.getDate() - nineWeeksInDays); return nineWeeksAgo } const findNextSunday = () => { const dateNineWeeksAgo = findNineWeeksAgo() // getting the exact day of the week that was 9 weeks ago let dayNineWeeksAgoe = dateNineWeeksAgo.getDay() // if the exact day is sunday ie 0 return that date in string format else find number of days to sunday add them to the exact date and reurn that. if (dayNineWeeksAgoe === 0) return dayNineWeeksAgoe.toString() else { let daysLeftToSunday = 7 - dayNineWeeksAgoe dateNineWeeksAgo.setDate(dateNineWeeksAgo.getDate() + daysLeftToSunday); return dateNineWeeksAgo.toString() } } console.log(findNextSunday())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.