如何使用JavaScript获取上周五的时间戳?

Dhi*_*iru 8 javascript

我必须得到上周五的时间戳,但我不知道如何使用工作日获得时间戳.有人可以帮忙吗?

我想要得到的是上周五和今天之间的区别.

var now = new Date();
var time = now.getTime();
var fridayTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 13, 30, 00);
var timeDiff = time - fridayTime;
Run Code Online (Sandbox Code Playgroud)

我知道我没有为"fridayTime"编写正确的代码,但不确定正确的代码是什么.

sha*_*han 9

const t = new Date().getDate() + (6 - new Date().getDay() - 1) - 7 ;
const lastFriday = new Date();
lastFriday.setDate(t);
console.log(lastFriday);
Run Code Online (Sandbox Code Playgroud)


haz*_*zik 8

首先,您需要获得上周五的日期差异:

var now = new Date(),
    day = now.getDay();
Run Code Online (Sandbox Code Playgroud)

根据"上周五"对您的意义,请使用以下内容

  • 最近的星期五

    var diff = (day <= 5) ? (7 - 5 + day ) : (day - 5);

  • 如果今天是星期五,那么今天返回,否则最接近星期五

    var diff = (7 - 5 + day) % 7;

  • 上周五

    var diff = 7 - 5 + day;

然后从当前日期中减去它,并使用setDate函数将结果设置为日期对象.setDate函数将正确处理负数,分别改变月份和年份:

来自mdn:

如果dayValue超出了该月的日期值范围,则setDate()将相应地更新Date对象.例如,如果为dayValue提供了0,则日期将设置为上个月的最后一天.

var date = new Date();
date.setDate(now.getDate() - diff);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);

var friday = date.getTime();
Run Code Online (Sandbox Code Playgroud)

完整代码

function getLastFridayOf(date) {
    var d = new Date(date),
        day = d.getDay(),
        diff = (day <= 5) ? (7 - 5 + day ) : (day - 5);

    d.setDate(d.getDate() - diff);
    d.setHours(0);
    d.setMinutes(0);
    d.setSeconds(0);

    return d.getTime();
}
Run Code Online (Sandbox Code Playgroud)

仅举例来说,它取决于JS引擎,并可能产生不同的结果

new Date(getLastFridayOf('2015-05-01')).toDateString() 
-> Fri Apr 24 2015

new Date(getLastFridayOf('2015-05-19')).toDateString() 
-> Fri May 15 2015

new Date(getLastFridayOf('2015-05-16')).toDateString() 
-> Fri May 15 2015

new Date(getLastFridayOf('2015-05-15')).toDateString() 
-> Fri May 08 2015
Run Code Online (Sandbox Code Playgroud)