问题描述
希望有人可以帮助我。我试图编写一个函数来查找9周前的星期日,而不管今天的星期几使用javascript。
我尝试使用moment()。day(-56),但无法正常工作。还有其他方法可以做到这一点吗?
解决方法
这是您要找的吗?
console.log(moment().startOf('week').subtract(9,'weeks').format("MM-DD-yyyy"))
星期天是一周的开始,因此我们去那里寻找基准。然后,使用Momentjs减去函数从那里减去9周。格式化以方便输出。
,根据https://momentjscom.readthedocs.io/en/latest/moment/02-get-set/06-day/,您可以在9个星期日之前获得:
import scss from "rollup-plugin-scss";
export default {
input: "./src/scripts/main.js",output: {
file: "./build/js/main.min.js",format: "esm",},plugins: [
scss({
output: "./build/css/style.css",failOnError: true,runtime: require("sass"),}),],};
,
我认为您需要分别计算星期和工作日。试试这样的事情: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 i.e 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())
,
如果您选择仅使用本机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>
如果重复使用,可以放在两行函数中,例如:
<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.getDate()-(9*7+today.getDay()));
// alter display for # weeks ago with day-of-week offset
return lastSun9wksAgo;
}
alert(sundayPriorWeeks(9).toDateString());
</script>