I'm trying to get the same day of the year last week so i can compare some analytics.
Using moment i can easily do this
var today = new Date();
//Sunday 4 September 2016 - Week 36
var lastYear = new moment(today).subtract(12, 'months').toDate();
//Friday 4 September 2015 - Week 37
What i am trying to do is get the same 'Sunday' last year, so Sunday week 36 2015
Any idea how to do this?
I'm trying to get the same day of the year last week so i can compare some analytics.
Using moment i can easily do this
var today = new Date();
//Sunday 4 September 2016 - Week 36
var lastYear = new moment(today).subtract(12, 'months').toDate();
//Friday 4 September 2015 - Week 37
What i am trying to do is get the same 'Sunday' last year, so Sunday week 36 2015
Any idea how to do this?
Share Improve this question asked Sep 13, 2016 at 6:09 Cade EmberyCade Embery 4501 gold badge5 silver badges19 bronze badges3 Answers
Reset to default 14Here's what I came up with:
let today = moment();
let lastYear = moment().subtract(1, 'year')
.isoWeek(today.isoWeek())
.isoWeekday(today.isoWeekday());
It takes today as start point, subtracts a year, and sets the week and weekday to the ones from today.
So today (Tue Sept 13 2016, aka 2016-W37-2
) last year was Tue Sept 8 2015 (aka 2015-W37-2
).
As of version 2.0.0
moment.js supports .endOf('week')
method, try
var lastYear = moment().subtract(1, 'years').endOf('week');
This will give you a 23:59:59 time, so you might also want to call .startOf('day')
to get 00:00:00 of the same day:
var lastYear = moment().subtract(1, 'years').endOf('week').startOf('day');
Depending on your locale, your week may be from Monday to Sunday or from Sunday to Saturday, so I guess you'll have to account for that, too.
Edit
I've looked up documentation, and it appears you can set day of week this way, too:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
So in your case it will be
var lastYear = moment().day(-52 * 7); // a Sunday 52 weeks ago
Or the two methods combined
var lastYear = moment().subtract(1, 'years').day(7); // a Sunday after the date that was 1 year ago
// Typescript
var lastYear: moment.Moment = moment().subtract(1, "year");