简体   繁体   English

使用jQuery或JS从给定日期获取上一个星期六

[英]Getting last Saturday from a given date using jQuery or JS

I am trying to get the last Saturday from a given date. 我正在尝试从给定日期获取最后一个星期六。 If function argument is 9/12/2019 it should return 9/7/2019 . 如果函数的参数是9/12/2019 ,它应该返回9/7/2019

I have tried two methods below with no success: 我尝试了以下两种方法,但均未成功:

 function getLastSaturday(theDate) { debugger var dateToUse = new Date(theDate); var lastSaturday = new Date(new Date().setDate(dateToUse.getDate() - (dateToUse.getDay() == 0 ? 7 : dateToUse.getDay() + 1))); return lastSaturday; } function getLatestSaturday(theDate) { var dateToUse = new Date(theDate); var latestSaturday = new Date(new Date().setDate(dateToUse.getDate() - dateToUse.getDay() + 1)); return latestSaturday; } console.log(getLastSaturday('9/12/2019')); console.log(getLatestSaturday('9/12/2019')); console.log(getLastSaturday('8/5/2019')); 

Update 更新资料

Modified getLastSaturday(theDate) that works 修改后的getLastSaturday(theDate)有效

function getLastSaturday(theDate) {
    var dateToUse = new Date(theDate);
    var start = dateToUse.getDay() == 0 ? 7 : dateToUse.getDay();
    var target = 6; // Saturday

    if (target >= start)
        target -= 7;
    var lastSaturday = dateToUse.addDays(target - start);
    return lastSaturday;
}

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

Consider the line: 考虑这一行:

var lastSaturday = new Date(new Date().setDate(dateToUse.getDate() - (dateToUse.getDay() == 0 ? 7 : dateToUse.getDay() + 1)));

This gets the current date, then subtracts the day number of some other date. 这将获取当前日期,然后减去其他日期的天数。 All you need to do is subtract the date's day number + 1, eg 您需要做的就是减去日期的天数+1,例如

 function getLastSaturday(date) { // Copy date so don't modify original let d = new Date(date); // Adjust to previous Saturday d.setDate(d.getDate() - (d.getDay() + 1)); return d; } // Samples [new Date(2019,8,23), new Date(2019,8, 1), new Date(2019,8, 7), new Date(2019,8,12) ].forEach(d => console.log(d.toString() + ' => ' + getLastSaturday(d).toString() )); 

Also see get previous saturday's date and next friday's . 另请参阅获取上一个星期六的日期和下一个星期五的

Using the built–in parser for unsupported string formats is strongly recommended against, see Why does Date.parse give incorrect results? 强烈建议将内置的解析器用于不受支持的字符串格式,请参阅为什么Date.parse给出不正确的结果?

The date format "9/7/2019" is ambiguous, it represents 9 July to most people or 7 September to some. 日期格式“ 9/7/2019”含糊不清,对于大多数人来说代表7月9日,对于某些人来说代表9月7日。 The simplest way to avoid confusion is to use the month name rather than number. 避免混淆的最简单方法是使用月份名称而不是数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM