I have a user inputted date which I convert to a moment
var newDate = moment('01/02/2015');
What I need to do is get the previous friday relative to whatever date is passed in. How can I accomplish this?
I thought about doing something like this:
moment('01/02/2015').add('-1', 'week').day(5);
but wonder how reliable it would be.
I have a user inputted date which I convert to a moment
var newDate = moment('01/02/2015');
What I need to do is get the previous friday relative to whatever date is passed in. How can I accomplish this?
I thought about doing something like this:
moment('01/02/2015').add('-1', 'week').day(5);
but wonder how reliable it would be.
Share Improve this question edited Jun 17, 2015 at 18:59 hubson bropa 2,7702 gold badges31 silver badges35 bronze badges asked Jun 17, 2015 at 17:40 EnviousEnvious 6041 gold badge7 silver badges20 bronze badges 2- Have you tried something? – Satpal Commented Jun 17, 2015 at 17:42
- Yes I thought about doing something like this: moment('01/02/2015').add('-1', 'week').day(5); but wonder how reliable it would be. – Envious Commented Jun 17, 2015 at 17:43
1 Answer
Reset to default 25newDate.day(-2);
It's that easy. :)
day()
sets the day of the week relative to the moment object it is working on.
moment().day(0)
always goes back to the beginning of the week. moment().day(-2)
goes back two days further than the beginning of the week, i.e., last Friday.
Note: this will return to the Friday of the previous week even if newDate is on Friday or Saturday. To avoid this behavior, use this:
newDate.day(newDate.day() >= 5 ? 5 :-2);