Get same weekend last year using moment js

11,189

Solution 1

Here'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).

Solution 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

Solution 3

// Typescript

var lastYear: moment.Moment = moment().subtract(1, "year");
Share:
11,189
Cade Embery
Author by

Cade Embery

Updated on June 20, 2022

Comments

  • Cade Embery
    Cade Embery almost 2 years

    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?

  • Robert Dyjas
    Robert Dyjas almost 5 years
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
  • thezeenagari
    thezeenagari almost 5 years
    @robdy Its for getting last one year.
  • Basser
    Basser over 3 years
    This answer seems to fail for some edge case, e.g. '2020-12-31' maps to '2020-12-31'. I think it works if instead of subtracting one year you use .isoWeekYear(today.isoWeekYear() - 1)