最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - MomentJS get the previous friday - Stack Overflow

programmeradmin3浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 25
newDate.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);
发布评论

评论列表(0)

  1. 暂无评论