How to get timestamp of last Friday using JavaScript?
const t = new Date().getDate() + (6 - new Date().getDay() - 1) - 7 ;
const lastFriday = new Date();
lastFriday.setDate(t);
console.log(lastFriday);
First you need to get a date diff to last friday:
var now = new Date(),
day = now.getDay();
Depending on what "last friday" means to you, use following
nearest past friday
var diff = (day <= 5) ? (7 - 5 + day ) : (day - 5);
if today is friday, then return today, otherwise nearest past friday
var diff = (7 - 5 + day) % 7;
friday of the last week
var diff = 7 - 5 + day;
Then substract this from the current date, and set result to the date object using setDate
function. The setDate function will correctly handle negative numbers, changing month and year respectively:
From mdn:
If the dayValue is outside of the range of date values for the month, setDate() will update the Date object accordingly. For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month.
var date = new Date();
date.setDate(now.getDate() - diff);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
var friday = date.getTime();
Full code
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();
}
Following for example only, it depends on a JS engine, and may produce different results
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